ios 讓程序在後臺長久運行的方法

在以前,當應用被按Home鍵退出後,應用僅有最多5秒鐘的時間做一些保存或者清理資源的工作,但是應用可以調用UIApplication的beginBackgroundTaskWithExpirationHandler方法,讓應用最多有10分鐘的時間在後臺長久運行,這個時間可以用來做清理本地緩存、發送統計數據等工作。

讓程序在後臺長久運行的示例代碼如下:

//APPDelegate.h文件
@property (assign ,nonatomic) UIBackgroundTaskIdentifier backgroundUpdateTask;
//APPDelegate.m文件
- (void)applicationDidEnterBackground:(UIApplication *)application {
    [self beginBackgroundUpdateTask];
    //在這裏加上你需要長久運行的代碼
    [self endBackgroundUptateTask];
    
}
- (void)beginBackgroundUpdateTask{
    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUptateTask];
    }];
}
- (void)endBackgroundUptateTask{
    [[UIApplication sharedApplication] endBackgroundTask:self.backgroundUpdateTask];
    self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}
_____________來自iOS開發進階(唐巧)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章