当我在模拟器上运行此代码时,它运行完美,但它在真实设备上崩溃?
问题描述:
当我在模拟器上运行此代码时,它运行完美,但它在真实设备上崩溃?当我在模拟器上运行此代码时,它运行完美,但它在真实设备上崩溃?
var num = 0 //or 1
notificationTime = ["2016-05-30 19:59:42 +0000","2016-05-15 16:54:22 +0000"]
if notificationTime[num] != ""
{
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
var newString = NSString(string: "\(notificationTime[num])")
var str1 = newString.substringToIndex(10)
var str2 = newString.substringFromIndex(11)
var finalStr = str1 + "T" + str2
var dateAsString = finalStr
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let newDate = dateFormatter.dateFromString(dateAsString)!
}
它说在最后的代码中,它是零,当我在真实设备上运行它,在模拟器上完美工作!
var arrLocalNotif = UIApplication.sharedApplication().scheduledLocalNotifications
for localN:UILocalNotification in arrLocalNotif!
{
var notificationFireDate:NSDate = localN.fireDate!
if notificationFireDate == newDate
{
UIApplication.sharedApplication().cancelLocalNotification(localN)
}
}
答
看来,UILocalNotification
实例中的一个不具有fireDate
,但你强行解开它。你可能想要的东西,而不是你得到了什么,此刻是这样的:
for localN:UILocalNotification in arrLocalNotif! {
if let notificationFireDate = localN.fireDate where notificationFireDate == newDate {
UIApplication.sharedApplication().cancelLocalNotification(localN)
}
}
答
看起来有日期的设备和模拟器不同解析。您使用NSLocale.currentLocale()
初始化日期格式化程序。如果您在设备和模拟器上使用不同的语言环境,则可能会出现问题。
在设备上调用dateFromString
之后,您可以检查newDate
是否不是nil
。
如果日期格式问题,然后尝试的方式将其设置为你的日期字符串格式化,或者使用NSCalendar
API来合成,而不是从字符串中解析它,你需要为NSDate
对象日期。
答
如果您将日期作为字符串传递以用作数据(也就是不显示给用户),并且您希望在每一端都进行可靠的转换,那么请使用ISO日期格式并将日期格式化程序的语言环境设置为en_US_POSIX
,如苹果在“解析日期字符串”here。
否则,您将在某些时候失败,因为其他语言环境将受到用户设置的影响,并在设备之间不同。当然,不要使用NSDateFormatter
上的“样式”选项。它们用于从日期创建面向用户的字符串,不应该用于将字符串转换为日期。
和崩溃的原因是?最后的代码是什么意思?是新的日期吗? –
同意你得到什么崩溃错误? –
模拟器和设备是否有相同的iOS版本? – rob180