user1150308
user1150308

Reputation: 33

Schedule notification in background task

I'm developing a Calendar/Alarm app for iOS which is synchronising with a web server. When an activity is added on the server, a push notification is sent out so that the iOS client can fetch the new data and, if needed, update and schedule the time for next alarm (local notification).

But this only works when the app is open on client side. I would like the client to receive the push notifications and if needed, re-schedule the time for next alarm in background.

Is this impossible on iOS?

Upvotes: 3

Views: 1956

Answers (2)

Yogesh shelke
Yogesh shelke

Reputation: 468

// use this methods in Appdeleagte
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {

    [self showAlarm:notification.alertBody];
    application.applicationIconBadgeNumber = 1;
    application.applicationIconBadgeNumber = notification.applicationIconBadgeNumber-1;
}

//  call this  in appdelagete
-(void)makeNotificationRequest:(UILocalNotification *)notification1
{
    [self showAlarm:notification1.alertBody];
}

// call this mathods in appdelagte
- (void)showAlarm:(NSString *)text {

**strong text**
// set notification and call this notification methods your another view ..... 
  [[NSNotificationCenter defaultCenter] postNotificationName:@"uniqueNotificationName" object:self]; //leak

}

Upvotes: 0

remingtonspaz
remingtonspaz

Reputation: 73

You can use Background Fetch for this, where the OS will "wake up" your app periodically to perform data fetching in the background.

First, enable the background fetch capability for your app. In XCode 6, view your project, then go to the Capabilities tab, turn on Background Modes, and check Background Fetch.

Then you'll have to implement some codes in the App Delegate:

In application:didFinishLaunchingWithOptions:, add:

[application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];

The above sets how often you wish the system to "wake up" your app for background processes ideally. Note that the final frequency is determined by an algorithm in the iOS, so it may not always be this often.

-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
//fetch code here
completionHandler(UIBackgroundFetchResultNewData);

}

The above is the actual overridden function that is called during this period of background process. Remember to call the completionHandler - failing to do so might reduce the chance of your app being run in the background next time (or so says the docs). The enums you may pass to the completionHandler are UIBackgroundFetchResultNewData, UIBackgroundFetchResultNoData, UIBackgroundFetchResultFailed. Use one of these depending on the result of your fetch.

Upvotes: 1

Related Questions