Schedule notification in background task

亡梦爱人 提交于 2019-12-11 09:37:18

问题


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?


回答1:


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.




回答2:


// 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

}


来源:https://stackoverflow.com/questions/27066239/schedule-notification-in-background-task

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!