Swift實現(xiàn)(在AppDelegate對應(yīng)的方法中添加如下代碼)
funcapplicationDidEnterBackground(application:UIApplication) {
? ? //創(chuàng)建一個定時器
? ? timer=NSTimer.scheduledTimerWithTimeInterval(1.0, target:self, ?selector:Selector("logAgain:"), userInfo:nil, repeats:true)
? ? //添加到主runloop中
? ? NSRunLoop.mainRunLoop().addTimer(timer!, forMode:NSDefaultRunLoopMode)
? ? letapp =UIApplication.sharedApplication()
? ? //如果后臺任務(wù)關(guān)閉,就從新開啟
? ? varbgTask:UIBackgroundTaskIdentifier? =UIBackgroundTaskInvalid
? ? bgTask = app.beginBackgroundTaskWithExpirationHandler{ () ->Voidin
? ? dispatch_async(dispatch_get_main_queue(), { () ->Voidin
? ? ? ? ifbgTask !=UIBackgroundTaskInvalid{
? ? ? ? bgTask =UIBackgroundTaskInvalid
? ? ? ? ? }
? ? })
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () ->Voidin
ifbgTask !=UIBackgroundTaskInvalid{
bgTask =UIBackgroundTaskInvalid
}
})
}
}
//進入前臺,關(guān)閉timer
funcapplicationWillEnterForeground(application:UIApplication) {
? ? iftimer!=nil{
? ? timer?.invalidate()
? ? timer=nil
? ? }
}
//timer的執(zhí)行函數(shù)
funclogAgain(timer:NSTimer){
print("hello world")
}
OC實現(xiàn)(在AppDelegate對應(yīng)的方法中添加如下代碼)
- (void)applicationDidEnterBackground:(UIApplication *)application {
? ? self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self ? ? ? selector:@selector(logAgain:) userInfo:nil repeats:YES];
? ? [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
? ? UIApplication* app = [UIApplication sharedApplication];
? ? self.bgTask = UIBackgroundTaskInvalid;
? ? __weak __typeof (&*self)weakSelf = self;
? ? self.bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
? ? dispatch_async(dispatch_get_main_queue(), ^{
? ? ? ? ?if (weakSelf.bgTask != UIBackgroundTaskInvalid) {
? ? ? ? ? ? ? ? weakSelf.bgTask = UIBackgroundTaskInvalid;
? ? ? ? ?}
? ? });
? ? dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
? ? ? ? ? ? ?if (weakSelf.bgTask != UIBackgroundTaskInvalid) {
? ? ? ? ? ? ? ? ? ? ?weakSelf.bgTask = UIBackgroundTaskInvalid;
? ? ? ? ? ? ?}
? ? ? });
}];
}
- (void)logAgain:(NSTimer*)timer{
//無限后臺
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
? ? ? ? ? ?if (self.timer != nil) {
? ? ? ? ? ? ? ? ? ?[self.timer invalidate];
? ? ? ? ? ? ? ? ? ?self.timer = nil;
? ? ? ? ? ?}
}