iOS7 Background Fetch 的实现过程

iOS7中加入了后台获取(Background Fetch)的特性,这个特性使得用户在打开应用之前应用就可以执行部分代码,比如准备数据,刷新UI等等。这个时常一般最大是30秒。

以下是设置Background Fetch的基本步骤,记录一下。

 

1. 点击Target下的Capabilities ->>Background Modes ->>Background fetch 打钩。

 

2. 设置fetch最短间隔

可以直接在AppDelegate里面的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法内加上

[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];

UIApplicationBackgroundFetchIntervalMinimum 是告诉系统尽可能频繁的进行Background fetch,但是这个频率多频繁呢?这个是系统自己决定的,开发者就无法得知啦。

即使你把 MinimumBackgroundFetchInterval 设的很小,系统也只能保证在这个时间段内程序不会被唤醒,而不是说每过这么长时间就会被唤醒。因此,开发者应该理性设置唤醒的时间,根据程序的具体情况来考虑。

 

3. 接下来就可以实现这个带Block回调的 Background fetch 的代理方法了。

在这里我们可以进行网络请求查看是否数据有更新。不过因为超时限制是 30秒,所以若超过这个时间,就需要使用Background Transfer Service。

我在这个方法里面写了一个本地通知用来测试。

//-------------------------------------------------------------
#pragma mark - Background fetch related delegate
//-------------------------------------------------------------

- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    NSLog(@"我就是传说中的Background Fetch??");
    UILocalNotification * localNoti = [[UILocalNotification alloc] init];
    localNoti.hasAction = YES;
    //滑动来...
    NSArray * actionMsgs = @[@"查看一个巨大的秘密",@"看看小伙伴在做什么",@"看美女图片",@"领取奖品",@"看看洪哥在做什么",@"掏钱买下一个DropBeacon",@"请世文吃饭"];
    localNoti.alertAction = [actionMsgs objectAtIndex:arc4random()%actionMsgs.count];
    localNoti.alertBody = @"我就是传说中的Background Fetch??";
    [[UIApplication sharedApplication] scheduleLocalNotification:localNoti];
    completionHandler(UIBackgroundFetchResultNewData);
}

 

4. 接下来就可以进行测试了。

测试的方法有两种。

第一种可以在RunScheme的选项中勾选Launch due to a background fetch event,如下图

 

第二种方式是选择Xcode 菜单栏的 Debug下的 Simulate Background Fetch来将模拟器直接切换到 Background Fetch状态,如下图

 

iOS7 Background Fetch 的实现过程,,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。