在Swift 3中检查launchOptions

时间:2016-10-18 15:48:22

标签: ios swift3

我已将代码转换为swift 3并已提交至应用商店。当他们打开应用程序时,它会在第一时间崩溃。结果,我检查了我的崩溃日志,它在这一行崩溃了。

    if let myLaunchOptions: NSDictionary = launchOptions as NSDictionary? {

我的整体代码是这样的。我知道launchOptions可能是零,甚至可能不是NSDictionary。这就是为什么我这样检查它并且它在那条线上失败了。我可以知道用swift 3检查/预防的其他方法吗?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    if let myLaunchOptions: NSDictionary = launchOptions as NSDictionary? {
        let test = myLaunchOptions[UIApplicationLaunchOptionsKey.userActivityDictionary] as! NSDictionary
        let userActivity = test["UIApplicationLaunchOptionsUserActivityKey"] as! NSUserActivity
        NSLog("test1:" + String(describing: userActivity))
        continueUserActivity(userActivity)
        }

我的崩溃日志在这里。

enter image description here

2 个答案:

答案 0 :(得分:13)

您应该检查并获取以下用户活动:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    if let userActivityDictionary = launchOptions?[.userActivityDictionary] as? [UIApplicationLaunchOptionsKey : Any],
        let userActivity = userActivityDictionary[.userActivityType] as? NSUserActivity {
        continueUserActivity(userActivity)
    }

    return true
}

答案 1 :(得分:3)

我必须更新@David Rodrigues的解决方案才能在Swift 4中运行,因为.userActivityTypeNSString

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    if let userActivityDict = launchOptions?[.userActivityDictionary] as? [AnyHashable : Any],
        let userActivity = userActivityDict["UIApplicationLaunchOptionsUserActivityKey"] as? NSUserActivity {
        continueUserActivity(userActivity)
    }

    return true
}