如何在Swift中检查launchOptions?

时间:2014-07-20 02:06:56

标签: swift

我在这里很难过 - 我试图检测我的应用是否是从LocalNotification发起的。但是我的所有代码都被塞满了。

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

这两个都失败并显示消息

"unexpectedly found nil while unwrapping an Optional value"

我确信我在做一些非常基本的错误。有什么指针吗?

2 个答案:

答案 0 :(得分:9)

最干净的方式:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    if let notification:UILocalNotification = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification {
        //do stuff with notification
    }
    return true
}

答案 1 :(得分:8)

你也可以这样做,

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