最近再做一個(gè)類似于“駕考寶典”的iOS應(yīng)用胚想,當(dāng)然作為考試計(jì)時(shí)的功能肯定不會(huì)少瞬场,開發(fā)期間也是遇到各種各樣的小問題械馆,本文所講為其中之一:iOS程序進(jìn)入后臺(tái)后十分鐘之內(nèi)就會(huì)被系統(tǒng)kill掉央渣,怎么解決呢涩惑?我想要程序進(jìn)入后臺(tái)后仍然運(yùn)行計(jì)時(shí)功能低飒,否則就無法達(dá)到考試的目的许昨,之后在網(wǎng)上查閱了相關(guān)資料最后終于找到答案,其精髓就是:利用蘋果給出的三種類型的程序可以保持在后臺(tái)運(yùn)行:音頻播放類褥赊,位置更新類糕档,另外一個(gè)記不太清楚了,我利用了蘋果給出的音頻播放類的這個(gè)“特權(quán)”來滿足我程序上的要求拌喉,詳細(xì)步驟如下:
1速那、步驟一:在Info.plist中,添加"Required background modes"鍵尿背,value為:App plays audio
步驟二:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window=[[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];//Override point for customization after application launch.NSError *setCategoryErr =nil;
NSError*activationErr? =nil;
[[AVAudioSession sharedInstance]
setCategory: AVAudioSessionCategoryPlayback
error:&setCategoryErr];
[[AVAudioSession sharedInstance]
setActive: YES
error:&activationErr];
self.window.backgroundColor=[UIColor whiteColor];
[self.window makeKeyAndVisible];returnYES;
}
步驟三:將以下代碼添加到appDelegate文件中的- (void)applicationDidEnterBackground:(UIApplication *)application函數(shù)端仰,也可添加到在具體類中注冊(cè)的應(yīng)用進(jìn)入后臺(tái)后的通知方法
- (void)applicationDidEnterBackground:(UIApplication *)application{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;
}
});
});
}
完成以上步驟你會(huì)發(fā)現(xiàn),程序進(jìn)入后臺(tái)后仍可運(yùn)行定時(shí)器田藐!