Reputation: 311
I am creating a game in which the user is rewarded points while the app is in the background or not running. If the application is fully closed out, they should still get points. Currently I am doing this using an NSTimer, however I have read everywhere that timers can not execute in the background. Here is what I have and how should I fix it:
- (void)applicationDidEnterBackground:(UIApplication *)application {
score = [[NSUserDefaults standardUserDefaults] integerForKey:@"score"];
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(score) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
-(void) score{
score++;
[[NSUserDefaults standardUserDefaults] setInteger:score forKey:@"score"];
}
Upvotes: 0
Views: 35
Reputation: 126
You can set a "end time" with NSUserDefault in applicationDidEnterBackground
method.
In applicationDidBecomeActive
you get the elapsed time since the "end time" and you set your score from this elapsed time.
Upvotes: 1