John55
John55

Reputation: 311

Excute Scoring Tasks in Game in Background objective-c

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

Answers (1)

lafalex
lafalex

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

Related Questions