Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check launchOptions in Swift?

Tags:

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?

like image 551
bitops Avatar asked Jul 20 '14 02:07

bitops


2 Answers

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
}
like image 61
bjtitus Avatar answered Nov 15 '22 11:11

bjtitus


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
}
like image 23
Jesse Hull Avatar answered Nov 15 '22 13:11

Jesse Hull