简体   繁体   中英

When I run this code on a simulator it runs perfectly, however it crashes on a real device?

When I run this code on a simulator it runs perfectly, however it crashes on a real device?

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)!
}

It says in the last code that it is nil when I run it on a real device, on simulator works perfectly!

var arrLocalNotif = UIApplication.sharedApplication().scheduledLocalNotifications

for localN:UILocalNotification in arrLocalNotif!
{
    var notificationFireDate:NSDate = localN.fireDate!

    if notificationFireDate == newDate
    {
        UIApplication.sharedApplication().cancelLocalNotification(localN)
    }
}

It seems that one of the UILocalNotification instances does not have a fireDate , but you force unwrap it. You probably want something like this instead of what you got at the moment:

for localN:UILocalNotification in arrLocalNotif! {   
     if let notificationFireDate = localN.fireDate where notificationFireDate == newDate {
         UIApplication.sharedApplication().cancelLocalNotification(localN)
     }
}

Looks like there's dates are parsed differently on device and simulator. You initialize date formatter with NSLocale.currentLocale() . If you use different locales on device and simulator, it can be a problem.

You can check if newDate is not nil after calling dateFromString on device.

If problem in date formatter, then try to set it up the way as your date strings are formatted, or use NSCalendar API to synthesize dates you need as NSDate objects, instead of parsing it from string.

If you are passing dates as strings to use as data (that is, not displaying them to the user) and you want reliable conversion at each end then use ISO date formats and set your date formatter's locale to en_US_POSIX as described by Apple in "Parsing Date Strings" here .

Otherwise, you will fail at some point, since other locales will be affected by user settings and be different between devices. Certainly don't use the "style" options on NSDateFormatter . They are for creating user-facing strings from dates, and should never be used to convert strings into dates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM