在后台任务中计划通知



我正在为iOS开发一个与Web服务器同步的日历/闹钟应用程序。在服务器上添加活动时,将发送推送通知,以便 iOS 客户端可以获取新数据,并在需要时更新和安排下一次警报(本地通知)的时间。

但这仅在客户端打开应用程序时才有效。我希望客户端接收推送通知,如果需要,在后台重新安排下一个警报的时间。

这在iOS上是不可能的吗?

为此,您可以使用后台提取,操作系统将定期"唤醒"您的应用,以便在后台执行数据提取。

首先,为应用启用后台提取功能。在 XCode 6 中,查看您的项目,然后转到"功能"选项卡,打开"后台模式",然后选中"后台提取"。

然后,您必须在应用委托中实现一些代码:

application:didFinishLaunchingWithOptions:,添加:

[application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];

以上设置了您希望系统"唤醒"您的应用以进行后台进程的频率。请注意,最终频率由iOS中的算法确定,因此可能并不总是如此。

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

}

以上是在此后台进程期间调用的实际重写函数。请记住调用completionHandler - 如果不这样做,可能会降低您的应用程序下次在后台运行的机会(或者文档是这样说的)。你可以传递给completionHandler的枚举是UIBackgroundFetchResultNewDataUIBackgroundFetchResultNoDataUIBackgroundFetchResultFailed。根据您的抓取结果使用其中之一。

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

最新更新