Tommy Devoy
Tommy Devoy

Reputation: 13549

Set Up a Timer That Runs for the Life of an IOS App

I'm trying to figure out a way to have a timer that begins at the time that an app is installed and continues to run even when the app is in the background. I'm basically using the timer to periodically check the battery life of an external device that is linked to the phone. I've been told that the best way to do this is to use some sort of delegate calls to a timer function, but I'm fairly new to IOS and am pretty confused on how to do that. I know how to set up the timer and get the battery life, I'm however perplexed on how to keep the timer going through the life of the app. Any help you could give would be extreeemely appreciated! Thanks a bunch!

Upvotes: 1

Views: 850

Answers (3)

Imirak
Imirak

Reputation: 1333

Running an app in the background (forever) isn't possible.

But while your app is running... you can set the repeats parameter of the method scheduledTimerWithInterval:target:selector:userInfo:repeats: to YES.

Here's a link to running it in the background for a certain period of time to perform a relatively large task.

Upvotes: 4

Julien
Julien

Reputation: 3477

coneybeare is right. This is iOS policy, which is in place exactly to prevent what you are trying to do, i.e. exhaust the iPhone's (or iPad's) battery life.

Upvotes: 0

coneybeare
coneybeare

Reputation: 33101

run even when the app is in the background

Not possible. You can request an extra 10 minutes, but thats it. You will not be able to write your app as is.

For the timer part of your question, you can do this:

[NSTimer scheduledTimerWithTimeInterval:60.0
    target:self
    selector:@selector(checkBattery:)
    userInfo:nil
    repeats:YES];

But you should really be subscribing to the notifications on battery change events. Here is sample code from apple that shows how to do it.

Upvotes: 1

Related Questions