简体   繁体   中英

Unable to parse a date on real device, works in simulator

I have an app and if I try to run this app on real devices (iPhone 5S and 6) - Xcode shows error:

fatal error: unexpectedly found nil while unwrapping an Optional value 2017-04-11 00:43:58.724143+0200 APN[2153:475883] fatal error: unexpectedly found nil while unwrapping an Optional value

There is a block of code where is problem. But in simulator is all ok and correct.

let stringBefore = "Mon, 10 Apr 2017 11:39:24 +0000"

let startIndexDate = stringBefore.index(stringBefore.startIndex, offsetBy: 5)
let endIndexDate = stringBefore.index(stringBefore.endIndex, offsetBy: -15)

let rangeDate = startIndexDate..<endIndexDate
let stringAfter = stringBefore.substring(with: rangeDate)

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"

let date = dateFormatter.date(from: stringAfter)
dateFormatter.dateFormat = "dd.MM.yyyy"

let finish = dateFormatter.string(from: date!) // there is the problem but why in Simulator is ok?

I know that I can write

dateFormat = "EEE, dd MMM yyyy hh:mm:ss +zzzz"

but I would like to ask you where is the problem?

It's possible it's a weird time zone issue that your converter isn't handling. I can't know without some debugging.

Regardless, I would recommend using another DateFormatter to find your date rather than trying to parse the string:

let startingFormatter = DateFormatter()
startingFormatter.dateFormat = "EEE, dd MMM y HH:mm:ss Z"

let endingFormatter = DateFormatter()
endingFormatter.dateFormat = "dd.MM.yyyy"

let stringBefore = "Mon, 10 Apr 2017 11:39:24 +0000"
let actualDate = startingFormatter.date(from: stringBefore)

if let actualDate = actualDate {
    let finish = endingFormatter.string(from: actualDate) //result is "10.04.2017"
}
else {
    //handle error
}

Also, as a general rule, force unwrapping an optional ( date! ) is a bad idea unless you're 100% confident there is a value, (which you can't be in this case because you don't know what's happening under the hood), or are ok with your program crashing if that value doesn't exist.

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