如何在Swift中检查launchOptions?

5

我在这里碰到了一些麻烦 - 我正在尝试检测我的应用是否是从本地通知启动的。但是我的所有代码都出现了故障。

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"

我相信我在这里做了一些非常基础的错误。有什么指针吗?
3个回答

19

您正在解包 launchOptions 字典,但它经常是 nil。尝试解包为 nil 值将导致崩溃,因此在使用尾随感叹号进行解包之前,您需要检查它是否为 nil。正确的代码如下:

if let options = launchOptions {
    // use the unwrapped `options` variable here
} else {
    // `launchOptions` was `nil`, handle it accordingly
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
    if let options = launchOptions {
       // Do your checking on options here
    }

    return true
}

10

最清晰的方法:

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

8

您也可以这样做:

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

1
如果通知为nil,甚至在到达测试之前就会崩溃。你不应该写像"as! UILocalNotification!"这样的东西。 - Frederic Adda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接