beginBackgroundTaskWithExpirationHandler 告警

xcode 出现类似的 log:

Background Task 139 ("xxx"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this.

原因:
由于IOS sdk进行了更新,导致beginBackgroundTaskWithExpirationHandler 没有进行正确的调用,参考:

https://stackoverflow.com/questions/10319643/proper-use-of-beginbackgroundtaskwithexpirationhandler

正确调用方式参考代码:

- (void) doUpdate 
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        [self beginBackgroundUpdateTask];

        NSURLResponse * response = nil;
        NSError  * error = nil;
        NSData * responseData = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error];

        // Do something with the result

        [self endBackgroundUpdateTask];
    });
}
- (void) beginBackgroundUpdateTask
{
    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask];
    }];
}

- (void) endBackgroundUpdateTask
{
    [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
    self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}

注意以上代码只是告诉你begin和end配对调用的使用方式,具体代码的细节问题,要根据你自己的工程进行调整。


发表评论

电子邮件地址不会被公开。 必填项已用*标注