just
just

Reputation: 2020

How to do some work when push notification arrives?

I have an application, I got the push notifications, but I would like to do that if the device got a push notification my application do some work in the background without user interaction. Now I can do some work if the user tap on the notification, but it's not enough efficient for me.

Upvotes: 1

Views: 300

Answers (3)

pradip kikani
pradip kikani

Reputation: 637

  func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject])

   {
       if (state == UIApplicationState.Background || state == UIApplicationState.Inactive)
         {
            // Your Logic
         }
     }

// Write this method in AppDelegate.h or AppDelegate.swift File.

Upvotes: 1

darshan
darshan

Reputation: 1115

1. In Info.plist set UIBackgroundModes to remote-notification

<key>UIBackgroundModes</key>
<array>
    <string>remote-notification</string>
</array>

2. You need to implement following method in ApplicationDelegate

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler
{

   //Success
    handler(UIBackgroundFetchResultNewData);
}

3. Send Push notification with content-available: 1 so it will work like silent

aps {
content-available: 1
alert: {...}
}

Upvotes: 1

Kiran Jasvanee
Kiran Jasvanee

Reputation: 6564

When your push notification arrives, you can do some additional background work on didReceiveRemoteNotification delegate.

On your appDelegate.m file, add below application delegate method with dispatch_async code to run additional background execution.

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{


    //Background execution block
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        //Do some work if the user tap on the notification
    });
}

Upvotes: 0

Related Questions