Search code examples
swiftbackgroundnotificationspush-notificationbackground-process

Get notification when app is in background mode


I want to call a function when I receive a notification, even when my application is in background

I found a lot of question / answer on stackoverflow but in me it does not. So I will explain everything I 've done

i have background mode activate

here

my info.plist is good

here

in my didFinishLaunchingWithOption i have

    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Badge | .Sound | .Alert, categories: nil))
    application.registerForRemoteNotifications()

and i have

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    println("NOTIFICATION 4");
}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    println("NOTIFICATION FETCH");
}

but i can't see my log when i send my notification

my notification is send like this

    { deviceToken: XXXXX,
    expiration: 1442225011,
    identifier: 0,
    payload: 
    { 'content-available': '1',
    aps: { badge: 0, alert: 'Hello' } } }

I do not know what to do more ... I really can not receive this notification, nothing happens ( I receive the banner but no call to my function)

thank's a lot


Solution

  • As you can read in documents:

    The aps dictionary can also contain the content-available property. The content-available property with a value of 1 lets the remote notification act as a “silent” notification.

    so you should insert content-available in aps dictionary, like this:

    { deviceToken: XXXXX,
    expiration: 1442225011,
    identifier: 0,
    payload: 
    { aps: { 'content-available': '1', badge: 0, alert: 'Hello' } } }