I'm using following function to create Date from String. It works well on simulator. But it crashed on real iPhone.
String: "Tue May 23 23:19:41 +0800 2017"
The first picture is debugging information on real iPhone. The second one is debugging information on simulator.
func createDate(fromString string: String) -> Date {
let formatter = DateFormatter()
formatter.dateFormat = "EEE MMM dd HH:mm:ss zzz yyyy"
let date = formatter.date(from: string) //fatal error: unexpectedly found nil while unwrapping an Optional value
return date!
}
I even tried it on playground. It's really weird! Thanks!
you date format slightly wrong, please use the bellow example dateformat.
from the app docs
RFC 3339
wiki ISO 8601
For proper format, use Date Field Symbol Table
I bet it's crashing on the next line, not on the line you've commented. You're force-unwrapping the result. That force-unwrap will crash with the exact error you are reporting if the date conversion fails.
I call the
!
operator the "crash if nil" operator. You should not do that. You need to program defensively and return the optional, then write the calling code to handle the case where the conversion fails.Others have already pointed out that date formatters depend on the locale of the device, and if it's different your conversion could fail. Force the formatter's locale to a known locale if you want to give it literal strings who's format doesn't vary based on country and language.
this link may solve your problem.....
Swift