2014-06-30 131 views
3

我是iOS應用程序開發中的新蜜蜂。我想在iOS中創建後臺服務。我還想提及一天中的某個特定時間和間隔(每2小時)調用一次服務(一種警報調用服務)。當服務運行時,應執行一些獨立於應用程序狀態的任務,即應用程序可處於活動狀態或非活動狀態。它的任何例子或者實現的代碼片段都會幫助我實現這個功能。在iOS中運行後臺服務

+1

瞭解localNotification在蘋果文檔 https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Introduction.html HTTP:/ /www.appcoda.com/ios-programming-local-notification-tutorial/ – Alfa

回答

3

使用此代碼

- (void)applicationWillEnterForeground:(UIApplication *)application 
{ 

[Timer invalidate]; 
    Timer = nil; 
} 

- (void)applicationDidEnterBackground:(UIApplication *)application 
{ 
    NSLog(@"Background process is Start(EnterBackground)!"); 
    __block UIBackgroundTaskIdentifier bgTask ; 
    UIApplication *app = [UIApplication sharedApplication]; 
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
     [app endBackgroundTask:bgTask]; 
     bgTask = UIBackgroundTaskInvalid; 
    }]; 
    Timer = [NSTimer scheduledTimerWithTimeInterval:120.0f target:self selector:@selector(process) userInfo:nil repeats:YES]; 
} 
+0

你能解釋什麼是計時器嗎?它在代碼中發生錯誤。 –

+1

在.h文件中聲明NSTimer * Timer; –

+0

非常感謝。這工作! 但是,這是在背景中運行某些東西的正確方法嗎? iOS中有沒有類似服務的東西? –