iOS為了讓設(shè)備盡量省電饲嗽,減少不必要的開銷聘芜,保持系統(tǒng)流暢薄坏,因而對(duì)后臺(tái)機(jī)制采用墓碑式的“假后臺(tái)”趋厉。除了系統(tǒng)官方極少數(shù)程序可以真后臺(tái),一般開發(fā)者開發(fā)出來的應(yīng)用程序后臺(tái)受到以下限制:
1.用戶按Home之后胶坠,App轉(zhuǎn)入后臺(tái)進(jìn)行運(yùn)行君账,此時(shí)擁有180s后臺(tái)時(shí)間(iOS7)或者600s(iOS6)運(yùn)行時(shí)間可以處理后臺(tái)操作
2.當(dāng)180S或者600S時(shí)間過去之后,可以告知系統(tǒng)未完成任務(wù)沈善,需要申請(qǐng)繼續(xù)完成乡数,系統(tǒng)批準(zhǔn)申請(qǐng)之后,可以繼續(xù)運(yùn)行闻牡,但總時(shí)間不會(huì)超過10分鐘净赴。
3.當(dāng)10分鐘時(shí)間到之后,無論怎么向系統(tǒng)申請(qǐng)繼續(xù)后臺(tái)罩润,系統(tǒng)會(huì)強(qiáng)制掛起App玖翅,掛起所有后臺(tái)操作、線程割以,直到用戶再次點(diǎn)擊App之后才會(huì)繼續(xù)運(yùn)行金度。
項(xiàng)目中我們需要定時(shí)器在后臺(tái)持續(xù)運(yùn)行一段時(shí)間,以保證我們的app正確運(yùn)行,我們需要如下步驟
步驟一:
將plist文件中加入Required background modes?
App registers for location updates?
步驟二:
- (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.
? ? UIApplication*? app = [UIApplication sharedApplication];
? ? __block? ? UIBackgroundTaskIdentifier bgTask;
? ? bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
? ? ? ? dispatch_async(dispatch_get_main_queue(), ^{
? ? ? ? ? ? if (bgTask != UIBackgroundTaskInvalid)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? bgTask = UIBackgroundTaskInvalid;
? ? ? ? ? ? }
? ? ? ? });
? ? }];
? ? dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
? ? ? ? dispatch_async(dispatch_get_main_queue(), ^{
? ? ? ? ? ? if (bgTask != UIBackgroundTaskInvalid)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? bgTask = UIBackgroundTaskInvalid;
? ? ? ? ? ? }
? ? ? ? });
? ? });
}