NSTimer 선택자는 백그라운드에서 실행되지 않을 수도 있습니다. 백그라운드에서 음악을 재생하는 것과 같이 특정 권한을 등록하지 않은 경우 백그라운드에서 실제로 수행중인 작업이 요청한 권한과 직접적으로 관련이있는 경우 실행을 수행 할 수 없다는 가정하에 작업해야합니다 코드가 생성되는 동안 앱이 백그라운드로 처리되는 동안 해결 방법을 찾는 것보다 훨씬 더 잘 성공할 수 있습니다.
이 시나리오에서는 많은 시간이 지나면 이미지를 변경하려는 것처럼 보입니다. 응용 프로그램이 포 그라운드에있을 때 NSTimer를 가지고 있다고 가정하면 (메소드가 올바르게 작성되었다고 가정) appDidEnterBackground 및 appWillEnterForeground를 청취하고 알림을 게시하는 것이 좋습니다 (아래 예제 코드 참조).
AppDelegate.m
================
- (void)applicationDidEnterBackground:(UIApplication *)application
{
self.currentTime = [NSDate date];
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationNameForBecameActive object:nil userInfo:@{kUserInfoForBecameActive: self.currentTime}];
}
================
ViewController.m
================
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBecomeActive:) name:kNotificationNameForBecameActive object:nil];
}
- (void)didBecomeActive:(NSNotification *)notification
{
NSDate *sleepDate = notification.userInfo[kUserInfoForBecameActive];
NSTimeInterval secondsPassed = [[NSDate date] timeIntervalSinceDate:sleepDate];
if (secondsPassed >= timeFirstAd)
{
[self changeImage];
}
// reinitialize NSTimer
}
================
는 다른 방법으로는 appDidEnterBackground 및 appWillEnterForeground 모두에 대한 알림을 게시 할 수 및 NSTimer를 무효화하고 다시 시작과 함께, 거기에 시간을 절약 할 수 있습니다.