Search code examples
iosxcodeswifttimernstimer

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")
    }
}

Solution

  • 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.