ios - 后台模式在iOS 8中不起作用

标签 ios background xcode6

在我的应用程序中,我每分钟都会从服务器获取更新。对于后台,我正在使用代码

 UIApplication*  app = [UIApplication sharedApplication];
 bti = [app beginBackgroundTaskWithExpirationHandler:^{

    NSLog(@"Debug - Ending background task %d",bti);
    [app endBackgroundTask:bti];
    NSLog(@"Debug -  Background task %d ended",bti);
    bti = UIBackgroundTaskInvalid;

}];
NSLog(@"Debug - Starting background task %d",bti);

[NSTimer scheduledTimerWithTimeInterval:60.0 target: self
                               selector: @selector(anyTask) userInfo:nil repeats: YES];

但是应用程序在一段时间后终止并获取日志
{(
    <BKProcessAssertion: 0x15ddbf50> identifier: Background Content Fetching (79) process: DemoApp[628] permittedBackgroundDuration: 30.000000 reason: backgroundContentFetching owner pid:33 preventSuspend  preventThrottleDownUI  preventIdleSleep  preventSuspendOnSleep 
)}

我还使用了这样的背景获取:
-(void)application:(UIApplication *)application
    performFetchWithCompletionHandler:
     (void (^)(UIBackgroundFetchResult))completionHandler {
NSLog(@"Background fetch started...");
  [self repeatTask];
//    //---do background fetch here---


NSLog(@"Background fetch completed...");

}

任何帮助,将不胜感激 :)

最佳答案

您不能使用此技术无限期地在后台运行。您可以使用后台获取模式来允许您的应用轮询服务器(但频率为分钟或几小时),也可以让服务器使用推送通知来提醒您的应用有新内容。您当前的方法对电池不太友好

如果要使用后台获取模式,则需要以适当的结果调用提供的completionHandler-

completionHandler(UIBackgroundFetchResultNewData);

要么
completionHandler(UIBackgroundFetchResultNoData);

要么
completionHandler(UIBackgroundFetchResultFailed);

performFetchWithCompletionHandler:的末尾

例如
-(void)application:(UIApplication *)application
    performFetchWithCompletionHandler:
     (void (^)(UIBackgroundFetchResult))completionHandler {
         NSLog(@"Background fetch started...");
         if ([self repeatTask]) { // //---do background fetch here--- returns YES if new data
             completionHandler(UIBackgroundFetchResultNewData);
         }
         else {
             completionHandler(UIBackgroundFetchResultNoData);
         }
         NSLog(@"Background fetch completed...");
}

关于ios - 后台模式在iOS 8中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26231652/

相关文章:

css - 背景没有填满窗口的高度

html - 使用CSS在浏览器中绘制部分图像

swift - 自动将添加的行保存/加载到 TableView

ios - 调整文本大小以适应 Swift 中的标签

ios - Xcode 6 GM - CLLocationManager

iOS 自定义导航栏后退按钮标题在点击时消失

ios - 项目中 Xcode 生成的 missing required module 'SwiftShims' 错误

ios - ios中SocketIO的实现

iphone - 我可以从 Interface Builder 传递 'parameter' 以便我的 ViewController 类知道如何以不同的方式处理吗?

jQuery 检测 css 类是否有背景图片