bitops bitops -4 years ago 189
Swift Question

How to check launchOptions in Swift?

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?

Answer Source

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
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download