iOS 后台运行方法

应用能够调用UIApplicationbeginBackgroundTaskWithExpirationHandler方法,让应用最多有10分钟的时间在后台长久运行。这个时间能够用来作清理本地缓存、发送统计数据等工做。代码以下:git

// AppDelegate.h文件
@property (nonatomic, assign) UIBackgroundTaskIdentifier backgroundUpdateTask;

// AppDelegate.m文件
- (void)applicationDidEnterBackground:(UIApplication *)application {
    [self beginBackgroundUpdateTask];
    // 在这里加上你须要长久运行的代码
    [self endBackgroundUpdateTask];
}

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

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

附:个人博客地址github

相关文章
相关标签/搜索