Check for launching from UILocalNotification in Sw

2019-03-16 07:33发布

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.

2条回答
我只想做你的唯一
2楼-- · 2019-03-16 08:05

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
}
查看更多
祖国的老花朵
3楼-- · 2019-03-16 08:15

LaunchOptions will be nil if you launch the application directly. The code will be running if you launch the application through the notifications rather than launch the application directly.

If you launch the application directly, then you need some other ways to solve this. Like use the time of the LocalNotification and the current time, and decide which view to show.

查看更多
登录 后发表回答