您可以使用後臺任務的API調用一個方法,你已經轉到後臺運行之後(只要你的任務不走太長 - 通常約10分鐘是最大允許時間)。
iOS不讓定時器在應用程序背景時觸發,所以我發現在應用程序後臺調度後臺線程,然後將該線程置於睡眠狀態,具有與定時器相同的效果。
將下面的代碼在應用程序委託的- (void)applicationWillResignActive:(UIApplication *)application
方法:
// Dispatch to a background queue
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// Tell the system that you want to start a background task
UIBackgroundTaskIdentifier taskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
// Cleanup before system kills the app
}];
// Sleep the block for 5 seconds
[NSThread sleepForTimeInterval:5.0];
// Call the method if the app is backgrounded (and not just inactive)
if (application.applicationState == UIApplicationStateBackground)
[self performSelector:@selector(test)]; // Or, you could just call [self test]; here
// Tell the system that the task has ended.
if (taskID != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:taskID];
}
});
您在** AppDelegate.m文件方法**'applicationWillResignActive'然後'applicationDidEnterBackground'被調用。 – Rohan
謝謝。但是我的意思是,當它在後臺 – Rubinc
看看[如何以編程方式截取iPhone主屏幕](http://stackoverflow.com/q/13459682/593709) –