background fetch后台拉取数据

作者: 贝勒老爷 | 来源:发表于2016-12-02 14:11 被阅读774次

一,开启Background Fetch支持

  在XCode->TARGETS->Capabilities->Background Modes打开并添加Background Fetch.
  同时在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法中添加:
  [[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
  MinimumBackgroundFetchInterval参数值是两次Fetch时间间隔,不能保证每隔这个时间间隔都会调用。这里设置为UIApplicationBackgroundFetchIntervalMinimum,意思是尽可能频繁的调用我们的Fetch方法。

二,增加实现Fetch方法

- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{};

每次系统Fetch时都会调用该方法,我们可以在该方法中做刷新数据等操作,操作执行完成以后要调用completionHandlerblock(),比如:completionHandler(UIBackgroundFetchResultNewData);
文档中说系统会根据completionHandler(执行的时间)来估计此次Fetch的耗电等。如果耗时耗电比较多,可能会降低被调用的次数。但这个方法也不是不限时执行的,说是有30s的时间来执行操作。

completionHandler有三个参数:
  UIBackgroundFetchResultNewData 成功拉取数据
  UIBackgroundFetchResultNoData 没有新数据
  UIBackgroundFetchResultFailed 拉取数据失败或者超时

三,模拟Fetch事件
  在实际的IOS7环境中,Fetch事件是由系统管理的,app开发者无法预先知道Fetch事件达到的时机。但XCode也提供了Fetch事件的调试办法,在XCode上运行程序后,在Debug->Simulate Background Fetch.
  还有一种情况是app没有运行(不在前台也不在后台),被Fetch事件唤醒执行.这种情况的测试方法如下:

  Product->Scheme->Edit scheme 在Debug模式选中Options,点选Launch due to a background fetch event,运行即可。
  可以观察到当Fetch事件到来时,app先进入后台,再执行- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{}。

四,判断设备是否开启后台应用程序刷新功能

  折叠C/C++ Code复制内容到剪贴板
  if ([[UIApplication sharedApplication] backgroundRefreshStatus] != UIBackgroundRefreshStatusAvailable)
  {
  UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"您没有开启后台刷新,请在 设置->通用->应用程序后台刷新 中开启." delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
  [alertView show];
  [alertView release];
  }

相关文章

  • background fetch后台拉取数据

    一,开启Background Fetch支持 二,增加实现Fetch方法 每次系统Fetch时都会调用该方法,我们...

  • (后台获取)Background Fetch

    Background Fetch iOS后台获取实现。 请参阅: https://developer.apple....

  • git 使用记录(一):git pull/git fetch拉取

    我们常用git拉取数据,通常是用git pull,不过同时也有人在用git fetch,同是从远程仓库拉取数据下来...

  • iOS Background Modes

    关于iOS后台操作只介绍了目前公司项目需要用到的: 一、Background Fetch(后台获取) 后台获取干...

  • Git 进阶

    一、进阶命令 1.git fetch 到远程仓库中拉取所有本地仓库中还没有的数据,但只是拉取,不自动进行分支合并,...

  • Git---fetch

    $ git fetch #拉取分支,从远程仓库--->本地仓库$ git fetch --prune #本地删除远...

  • iOS Silent Remote Notification一步

    总所周知,苹果在iOS7.0后在后台任务上增加了如下新特性: 后台获取(Background Fetch) 推送唤...

  • fetch 命令

    fetch 命令会到远程仓库中拉取所有你本地仓库中还没有的数据。 该命令只是将数据拉取到本地,会新建一个分支,并不...

  • React第五天 (偷懒了一天)

    React与后台数据交互 axios: fetch: 传统 Ajax 已死,Fetch 永生:https://se...

  • Background Fetch

    Background Fetch Fetching Small Amounts of Content Opport...

网友评论

    本文标题:background fetch后台拉取数据

    本文链接:https://www.haomeiwen.com/subject/waxqmttx.html