Search code examples
iosnotificationsswiftuilocalnotification

iOS 8 Beta 6 - Handling a UILocalNotification when the app is in Background


I'm creating an app for creating alarms. If the app isn't in background or inactive everything work fine. But if the app is inactive (because i've pressed home button or i've pressed the lock button) when the notification occurs, after sliding or touching the banner, the code isn't executed and the app doesn't complete its actions.

I've read a lot of topics here and on the web but nothing can help me. Documentation says:

In iOS, you can determine whether an application is launched as a result of the user tapping the action button or whether the notification was delivered to the already-running application by examining the application state. In the delegate’s implementation of the application:didReceiveRemoteNotification: or application:didReceiveLocalNotification: method, get the value of the applicationState property and evaluate it. If the value is UIApplicationStateInactive, the user tapped the action button; if the value is UIApplicationStateActive, the application was frontmost when it received the notification.

But application:didReceiveLocalNotification: method seems not to be called after sliding or tapping the notification. This method isn't called when a notification occurs and the app is inactive. How can execute the code for notification handling if app is inactive?

this is my code:

func application(application: UIApplication!, didReceiveLocalNotification notification: UILocalNotification!)
{

    if(UIApplication.sharedApplication().applicationState == UIApplicationState.Active)
    {
        .

        println("Notification recieved and handled when inactive")

        .

    }

   .
   .
   .

}

All this code isn't executed when my application is in background or inactive or in lockscreen with my app still "alive" (when i push lock-screen button when my app is in foreground ). How can i handle Local Notification in these conditions? How can i recognize if the app is becoming active because of local notification occurs? I've found no solution to this problem.


Solution

  • two cases:

    1 . when your app is not running, only applicationDidFinishLaunching is called. (either never was or was killed)

    In that case, the launchOptions NSDictionary contain the UIApplicationLaunchOptionsLocalNotificationKey key


    2 . if it is running -regardless of the state- didReceiveLocalNotification is called

    In that case, use UIApplication.sharedApplication().applicationState to see where your app is

    note: with ios8 there is more to do for this to work