iOS背景提取任务问题:太罕见&锁定时不起作用

时间:2014-05-26 09:28:18

标签: ios objective-c ios7

在iOS 7及更高版本的设备上,我们需要我们的应用程序才能使用Background Fetch iOS API。我们需要这个,因为我们的服务器无法实现推送通知。为实现这一点,我做了以下事情:

  1. 将后台获取最小时间间隔设置为1 Min。

    [[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:TIMEINTRVAL_DIFFERANCE_IN_BACKGROUND_FETCH];
    
  2. 使用NSURLSession Code实现委托方法以下载图像。

      -(void)application:(UIApplication *)application
    performFetchWithCompletionHandler:
    (void (^)(UIBackgroundFetchResult))completionHandler {
    
    NSLog(@"Background fetch started...");
    
    UILocalNotification *notification = [[UILocalNotification alloc]init];
    
    [notification setAlertBody:@"backgroud fetch"];
    [[UIApplication sharedApplication] presentLocalNotificationNow:notification];
    
    // 1
    NSString *imageUrl =
    @"http://www.spotonsoft.com/images/logo.png";
    
    // 2
    NSURLSessionConfiguration *sessionConfig =
    [NSURLSessionConfiguration defaultSessionConfiguration];
    
    // 3
    NSURLSession *session =
    [NSURLSession sessionWithConfiguration:sessionConfig
                                  delegate:(id)self
                             delegateQueue:nil];
    
    NSURLSessionDownloadTask *getImageTask =
    [session downloadTaskWithURL:[NSURL URLWithString:imageUrl]];
    
    [getImageTask resume];
    
    NSLog(@"Background fetch completed...");
    }
    
    
    -(void)URLSession:(NSURLSession *)session
     downloadTask:(NSURLSessionDownloadTask *)downloadTask
    didFinishDownloadingToURL:(NSURL *)location
    {
    
        self.completionHandler(UIBackgroundFetchResultNewData);
    }
    
  3. 在" info.plist"中设置后台获取模式。

  4. 观察: -

    1. 调用后台提取,我可以在日志中看到它。但是,2次通话之间的平均持续时间太长。例如。很多次10-15分钟。
    2. 只有在手机未锁定时才会拨打电话。
    3. 我们可能做错什么吗?如果有的话,请与Background Fetch Task API分享您的经验。

2 个答案:

答案 0 :(得分:2)

  

系统根据用户的行为唤醒应用程序,旨在在用户启动应用程序之前触发后台提取。例如,如果用户总是在下午1点使用应用程序,系统将学习并调整,在使用期之前执行提取。

http://www.objc.io/issue-5/multitasking.html

完全可以预期,您会在背景提取之间看到10-15分钟的间隔。

您可以通过选择Debug - >触发从Xcode的菜单栏(在调试时)进行后台提取。 Simulate Background Fetch

答案 1 :(得分:0)

使用以下代码在应用程序后台状态下执行某些代码:

UIApplication *app = [UIApplication sharedApplication];
task = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:task];
        task = UIBackgroundTaskInvalid;
    }];
// Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // Do the work associated with the task.

        if (connectedToNetwork) {
            // do work son...
        }

        [app endBackgroundTask:task];
        task = UIBackgroundTaskInvalid;
    });