nachshon fertel
nachshon fertel

Reputation: 23

How to i add a timer to my app that will run even if the app is closed?

In the app that I'm making, the user will be only able to do a task every 2 hrs. How do I keep track of the 2 hrs even if the app is closed and not running?

Please give an answer in Swift. Here is my code so far

@IBAction weak var button(sender: AnyObject) {        
    if timer >= 2 hrs {    
       println("OK")    
    }    
    else {
       println("Please wait 2 hrs before continuing")
    }
}

Upvotes: 0

Views: 1415

Answers (3)

Victor Sigler
Victor Sigler

Reputation: 23449

It isn't possible to do as you please in the background. Unfortunately Apple doesn't let you run NSTimers on the background.

Regarding this article of Apple, for tasks that require more execution time to implement, you must request specific permissions to run them in the background without their being suspended. In iOS, only specific app types are allowed to run in the background:

  • Apps that play audible content to the user while in the background, such as a music player app
  • Apps that record audio content while in the background

  • Apps that keep users informed of their location at all times, such as a navigation app.

  • Apps that support Voice over Internet Protocol (VoIP).
  • Apps that need to download and process new content regularly.
  • Apps that receive regular updates from external accessories.

You can read more in the above article. I hope this help you.

Upvotes: 0

Shamas S
Shamas S

Reputation: 7549

Create an NSDate object and save it to user defaults. When the app restarts, fetch the object and compare the time difference. If 2 hours have elapsed, let the user perform the action. If there is still some time, start a new timer, based on the difference between the 2 time stamps.

Upvotes: 3

Jeef
Jeef

Reputation: 27285

Unfortunately, depending what you are doing, you may not be able to do this. Apple has very specific requirements for backgrounding "modes". By default I believe you have 10 minutes to complete running tasks while your app has been backgrounded. If you are unable to do that you will have to register for the appropriate backgrounding modes.

https://developer.apple.com/library/prerelease/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

If you are never going to submit your app to the app store I can give you a way to "trick" the app to keep running in the background.

If you are using some sort of notification web service you could probably set it up to work that way but as listed you are looking at a no.

  • For example: I believe you can register to receive remote notifications, register a task with a remote website which could then fire a notification to you application which could then notify the users. The users still would have to act on that notification, however.

Upvotes: 0

Related Questions