How to check startup options in Swift?

I'm pretty much worried here - I'm trying to determine if an application is running from LocalNotification or not. But all my code is met.

func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool { var firstWay = launchOptions.objectForKey(UIApplicationLaunchOptionsLocalNotificationKey) var secondWay = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey] return true } 

Both of them fail with the message.

 "unexpectedly found nil while unwrapping an Optional value" 

I am sure that I am doing something very simple here. Any pointers?

+5
source share
3 answers

Deploying the launchOptions dictionary, which is often zero, in your arguments. Attempting to expand the nil value will fail, so you need to verify that it is not zero before using the trailing exclamation point to expand 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 } 
+16
source

The 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 } 
+9
source

You can also do this,

 let notification = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as! UILocalNotification! if (notification != nil) { // Do your stuff with notification } 
+8
source

Source: https://habr.com/ru/post/972551/


All Articles