在后台任务中安排通知 [英] Schedule notification in background task

查看:96
本文介绍了在后台任务中安排通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这在iOS上是不可能的吗?

Is this impossible on iOS?

推荐答案

您可以使用后台提取功能,操作系统会定期唤醒您的应用以在后台执行数据提取。

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

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

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.

然后你必须在App Delegate中实现一些代码:

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

应用程序中:didFinishLaunchingWithOptions :,添加:

[application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];

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

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);

}

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

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.

这篇关于在后台任务中安排通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆