廢話不多說,上代碼
- (void)applicationDidEnterBackground:(UIApplication *)application {
??// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
??// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
???[self comeToBackground];
}
-(void)comeToBackground{
??//初始化一個后臺任務(wù)BackgroundTask,這個后臺任務(wù)的作用就是告訴系統(tǒng)當(dāng)前app在后臺有任務(wù)處理,需要時間
??UIApplication*?app = [UIApplication sharedApplication];
??self.bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
????[app endBackgroundTask:self.bgTask];
????self.bgTask = UIBackgroundTaskInvalid;
??}];
??//開啟定時器 不斷向系統(tǒng)請求后臺任務(wù)執(zhí)行的時間
??self.bgTimer = [NSTimer scheduledTimerWithTimeInterval:25.0 target:self selector:@selector(makeMoreTime) userInfo:nil repeats:YES];
??[self.bgTimer fire];
}
-(void)makeMoreTime {
??//如果系統(tǒng)給的剩余時間小于60秒 就終止當(dāng)前的后臺任務(wù)敏簿,再重新初始化一個后臺任務(wù),重新讓系統(tǒng)分配時間宣虾,這樣一直循環(huán)下去惯裕,保持APP在后臺一直處于active狀態(tài)。
??if ([UIApplication sharedApplication].backgroundTimeRemaining < 60) {
????[[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
????self.bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
??????[[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
??????self.bgTask = UIBackgroundTaskInvalid;
????}];
??}
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
??// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
//回到前臺將用到的timer銷毀绣硝,很重要
??[self.bgTimer invalidate];
??self.bgTimer = nil;
??[[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
??self.bgTask = UIBackgroundTaskInvalid;
}