Excute Scoring Tasks in Game in Background objective-c - ios

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"];
}

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.

Related

NSTimer not working after reset

I have a NSTimer which should be work when app in foreground but should stop when app goes to background. but if came again to foreground timer is not working. Is there any way to do that?
inbox.m
(viewDidLoad){
myTimer = [NSTimer scheduledTimerWithTimeInterval: 0.60 target: self selector: #selector(saveSlow) userInfo: nil repeats: YES];
if([[NSUserDefaults standardUserDefaults] boolForKey:#"enterBG"]==YES)
{
[myTimer invalidate];
myTimer = nil;
}
....
}
Have you reset the bool value of enterBG after the app enter foreground? If not, even the timer is generated, it'll be invalidated again later.
Another point, you generated your timer in -viewDidLoad, generally, the view life loop only invoke it one time. The next time your app enter foreground, it won't be invoked. This might be another reason why your timer won't works again. You can try put it to -viewWillAppear: instead. You need to invoke the code snippet manually.
And a suggestion, you'd better to use the related notification to handle the timer:
UIApplicationDidEnterBackgroundNotification
UIApplicationWillEnterForegroundNotification
you cant try this code in your project
UIBackgroundTaskIdentifier bgTask = UIBackgroundTaskInvalid;
UIApplication *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
}];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.60 target:self selector:#selector(timerMethod) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
-(void) timerMethod{
NSLog(#"in Vijay yadav ");
}
Try to remove:
[myTimer invalidate];
myTimer = nil;
As the timer will stop working in background after 3mins. When you came to foreground, it automatically runs. By invalidating and nil, you are removing the instance of your timer. In this case you again have to intialize the timer.

Keep NSTimer running even application goes in background in ios

I want to perform particular task in background continuously even my application goes in background.
Here is the code which i tried. Timer is firing only once when it enters in background.
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSTimer * timer = [NSTimer timerWithTimeInterval:2.0
target:self
selector:#selector(timerTicked)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer
forMode:NSDefaultRunLoopMode];
}
- (void) timerTicked
{
NSLog(#"Timer method");
}
You can't have a timer in background. It may work for a short time but your app will quickly goes into sleep mode if you don't have a registered background mode.
Available modes may be :
Audio
Location updates
Background fetch
Others ...
Take a look at Background execution documentation for more info
- (void)applicationDidEnterBackground:(UIApplication *)application {
UIBackgroundTaskIdentifier bgTask = UIBackgroundTaskInvalid;
bgTask = [[UIApplication sharedApplication]
beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
}];
// NotificationTimer its timer
// myMethod1 call ur method
NotificationTimer = [NSTimer scheduledTimerWithTimeInterval: Interval
target: self
selector:#selector(myMethod1)
userInfo: nil repeats:YES];
}
I think its help to u

How to repeate NSTimer every day at particular time in iOS app

I have method which call the sqlite method to get data and then display count to application badge number in ip. I want that the method should be called every day at 12.5 am so that it has new count for the day. I am doing in following way:
[NSTimer scheduledTimerWithTimeInterval:300 target:self selector:#selector(makeNotificationRequest:) userInfo:nil repeats:YES];
I am calling this NSTimer in when application goes in background state.
-(void)makeNotificationRequest:(NSTimer *)timer {
[self repeatedMethod];
}
- (void)repeatedMethod {
SOWObject *object =[[SOWObject alloc]init];
[object getBadgeNumber:[self getDBPath]];
[UIApplication sharedApplication].applicationIconBadgeNumber=badgeArray.count;
}

NSTimer while in background mode is working -- but shouldn't it NOT be working?

I've opted in to background location updates in an App I'm working on.
In my LocationManager class, I've got a method that looks like this:
- (void)beginUpdateTimer
{
[self.updateTimer invalidate];
self.updateTimer = [NSTimer timerWithTimeInterval:ForceUpdateDuration
target:self
selector:#selector(updateWithLastKnownLocation)
userInfo:nil
repeats:NO];
NSRunLoop *runloop = [NSRunLoop currentRunLoop];
[runloop addTimer:_updateTimer forMode:NSRunLoopCommonModes];
}
The method -updateWithLastKnownLocation potentially calls beginUpdateTimer again.
In testing my app, I've discovered that the timer continues to fire upon the app moving in to the background, so long as I've enabled background location updates. Shouldn't this NOT be happening though? Can I rely on this?
Thanks!
Yes, you can rely on it, provided the timer was running at the time you went into the background.

selector method of NSTImer called twice in beginBackgroundTaskWithExpirationHandler

In my beginBackgroundTaskWithExpirationHandler code block in '-applicationDidEnterBackground' method, I have nstimer implemented as follows:
UIBackgroundTaskIdentifier taskId = [application beginBackgroundTaskWithExpirationHandler:^{
timer = [NSTimer scheduledTimerWithTimeInterval:0.0 target:self selector:#selector(print:) userInfo:nil repeats:NO];
}];
And Eventhough its repeats:NO, 'print'method as the selector is called twice, which i can see through NSLog.
This timer hasn't be called from any where else than in applicationDidEnterBackground.
I assure you that there is nothing wrong with:
timer = [NSTimer scheduledTimerWithTimeInterval:0.0 target:self selector:#selector(print:) userInfo:nil repeats:NO];
Your 'print' method wil NOT be called twice. Your problem is with something else.
And another thing, a timer with a 0.0 time interval is rather pointless wouldn't you agree?

Resources