omg
omg

Reputation: 17

Checking if iOS app was launched from local notification?

How do you detect if an app that is NOT in an active, inactive, or background state (terminated) is launched from a local notification? So far, I've tried two methods in the App Delegate's didFinishLaunchingWithOptions:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // METHOD 1:
    if let options = launchOptions {
        if let key = options[UIApplicationLaunchOptionsLocalNotificationKey] {
            notificationCenter.postNotification(NSNotification(name: "applicationLaunchedFromNotification", object: nil))
        }
    }

    // METHOD 2:
    let notification = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as! UILocalNotification!
    if (notification != nil) {
        notificationCenter.postNotification(NSNotification(name: "applicationLaunchedFromNotification", object: nil))
    }

    return true
}

In my View Controller, I observe for the notification in ViewDidLoad and in response, set a UILabel's text:

override func viewDidLoad() {
    super.viewDidLoad()
    notificationCenter.addObserver(self, selector: "handleAppLaunchFromNotification", name: "applicationLaunchedFromNotification", object: nil)
}

func handleAppLaunchFromNotification() {
    debugLabel.text = "app launched from notification"
}

But the UILabel's text is never set after launching the terminated app from a local notification.

My questions are:

  1. What am I doing wrong?
  2. Is there an easier way to debug a situation like this other than setting a UILabel? Once the app is terminated, Xcode's debugger detaches the app and I can't use print().

Upvotes: 1

Views: 1398

Answers (1)

Ashish P.
Ashish P.

Reputation: 858

You are checking local notification in didFinishLaunchingWithOptions this methods contains launchOptions for only remote notifications. If app is in terminated state and you perform action on local notification then didReceiveLocalNotification gets call after didFinishLaunchingWithOptions method.

Upvotes: 0

Related Questions