3

I have converted my codes to swift 3 and I have submitted to app store. When they open app, it crash at first time. As a result, I check my crashlog and it crash at this line.

    if let myLaunchOptions: NSDictionary = launchOptions as NSDictionary? {

My overall code is like this. I know that launchOptions can be nil and it might not even be NSDictionary. That's why I have checked like that and it fail at that line. May I know how else to check/prevent with 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)
        }

My crash log is here.

enter image description here

Khant Thu Linn
  • 5,905
  • 7
  • 52
  • 120

2 Answers2

14

You should be checking and obtaining user activity like this:

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
}
David Rodrigues
  • 844
  • 6
  • 6
9

I had to update @David Rodrigues' solution in order to make this work in Swift 4 because .userActivityType is NSString.

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
}
skornos
  • 3,121
  • 1
  • 26
  • 30