Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for launching from UILocalNotification in Swift

This is a follow-up question to How to check launchOptions in Swift? - I got my app to launch successfully without crashing, but I can't seem to correctly detect when the app is launching from a notification vs a normal launch.

I am creating my UILocalNotification like so:

// set up a frequently recurring notification here just for testing...
var fast = UILocalNotification()
fast.fireDate = NSDate(timeIntervalSinceNow: 15)
fast.alertBody = "Alert Message"
fast.timeZone = NSTimeZone.localTimeZone()
fast.repeatInterval = NSCalendarUnit.CalendarUnitMinute
fast.userInfo = ["Important":"Data"]
UIApplication.sharedApplication().scheduleLocalNotification(fast)

And this is my code for trying to handle when the app is launched from a UILocalNotification.

func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
    if var launch = launchOptions {
        if var key = launch.objectForKey(UIApplicationLaunchOptionsLocalNotificationKey) {
            // I never seem to reach this point...
        }
    }
    return true
}

If my app is backgrounded and I tap on the alert box, the action I want to fire is executed correctly, so I know that I at least can get one path working. The issue here is launching the application completely from a notification.

like image 939
bitops Avatar asked Jul 20 '14 23:07

bitops


1 Answers

If your App is running in background, the "application didFinishLaunching" method will not be called. It has already been launched.

In this case you should do your job in the "application didReceiveLocalNotification" method.

func application(application: UIApplication!, didReceiveLocalNotification notification: UILocalNotification!) {
        // do your jobs here
}
like image 107
Louis Zhu Avatar answered Nov 08 '22 19:11

Louis Zhu