Reputation: 23
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
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 record audio content while in the background
Apps that keep users informed of their location at all times, such as a navigation app.
You can read more in the above article. I hope this help you.
Upvotes: 0
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
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.
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.
Upvotes: 0