0

I was wondering what's the best practice to increase resources in an iPhone application (no matter if it's running in the foreground or it's frozen/running in background) The feat I'm trying to accomplish is basically to increment some coins every 15 minutes, no matter if the application is in foreground or background.

sigquit
  • 5
  • 1

4 Answers4

4

When your application is running you can achieve this using an NSTimer. However, when you app is in the background the timer will not fire.

Use the applicationDidEnterBackground and applicationWillEnterForeground methods of you AppDelegate to detect when the app enters / exits background state - incrementing your coin count based on the current time.

ColinE
  • 68,894
  • 15
  • 164
  • 232
1

You could accomplish this by finding the time difference between the first and the last launch(based on your requirementt) and then incrementing the coins based on the time difference finding the time interval between two dates

 NSTimeInterval noOfSeconds = [date timeIntervalSinceDate:date2];

//finding difference between two dates

noOfSeconds/900//this will give the number of 15 minutes elapsed
varun thomas
  • 357
  • 4
  • 14
1

It depends on what you are trying to do, but probably you don't need to do that in the background. Just store the Time Stamp for the last time the user checks the ammount of coins and with some math, calculate the current coins the next time he checks.

Odrakir
  • 4,254
  • 1
  • 20
  • 52
  • +1 Although I also upvoted ColinE's answer, I think this is better. This way, you only need the timer to force the display to refresh. – JeremyP Apr 22 '13 at 09:22
1

You can do like this:

NSTimer *timer;
timer= [NSTimer timerWithTimeInterval:15*60 //seconds
                                    target:self
                                    selector:@selector(yourMethod)
                                    userInfo:nil
                                    repeats:YES];

This is call the yourMethod every 15 minutes, and you can do your stuffs there.

Apart from above, please refer this:

iphone - NSTimers in background

Community
  • 1
  • 1
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140