I'm pretty stumped here - I'm trying to detect if my app launched from a LocalNotification or not. But all my code is borked.
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
var firstWay = launchOptions.objectForKey(UIApplicationLaunchOptionsLocalNotificationKey)
var secondWay = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey]
return true
}
Both of these fail with the message
"unexpectedly found nil while unwrapping an Optional value"
I am sure I am doing something very basic incorrectly here. Any pointers?
You are unwrapping the launchOptions dictionary, which is frequently nil, in your arguments. Trying to unwrap a nil value will lead to a crash so you need to check that it is not nil before using the trailing exclamation point to unwrap it. The correct code is as follows:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
if let options = launchOptions {
// Do your checking on options here
}
return true
}
cleanest way:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if let notification:UILocalNotification = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification {
//do stuff with notification
}
return true
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With