你可以按照兩個更好的結果。例如,當應用程序從didFinishLaunchingWithOptions激活時使用選項2:以及從 啓用應用程序時的選項1 - (void)applicationDidBecomeActive:(UIApplication *)application或 - (void)applicationWillEnterForeground:(UIApplication *)應用程序 選項1--最簡單的方法是在後臺運行循環中安排NSTimer。我建議您的應用程序委託實現以下代碼,並從applicationWillResignActive調用setupTimer :.
- (void)applicationWillResignActive:(UIApplication *)application
{
[self performSelectorInBackground:@selector(setupTimerThread) withObject:nil];
}
-(void)setupTimerThread;
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSTimer* timer = [NSTimer timerWithTimeInterval:10 * 60 target:self selector:@selector(triggerTimer:) userInfo:nil repeats:YES];
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:timer forModes:NSRunLoopCommonModes];
[runLoop run];
[pool release];
}
-(void)triggerTimer:(NSTimer*)timer;
{
// Do your stuff
}
中的appDelegate
.H
中的appDelegate .M
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UIApplication* app = [UIApplication sharedApplication];
// Request permission to run in the background. Provide an
// expiration handler in case the task runs long.
NSAssert(bgTask == UIBackgroundTaskInvalid, nil);
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
// Synchronize the cleanup call on the main thread in case
// the task actually finishes at around the same time.
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid)
{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
});
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do the work associated with the task.
// Synchronize the cleanup call on the main thread in case
// the expiration handler is fired at the same time.
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid)
{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
});
});
NSLog(@"app entering background");
/*
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.
*/
}
或者你可以在後臺線程通過像這樣運行的NSTimer(我
UIBackgroundTaskIdentifier bgTask;
我故意漏出線程對象):
-(void)startTimerThread;
{
NSThread* thread = [[NSThread alloc] initWithTarget:self selector:@selector(setupTimerThread) withObject:nil];
[thread start];
}
嘗試使用上面的代碼。我們使用這兩個選項對我們來說工作正常。祝你好運
你可以在你的計時器中進行一個exit()調用...不是由蘋果指南推薦的,但它可以工作。 – 2012-01-17 12:55:02
考慮當您的應用程序處於後臺時,您選擇的方法如何與用戶在設備上更改當前日期和時間進行交互。有很多應用程序的安全性可以通過這種方式繞過。 – 2012-01-17 17:21:57