swag swag - 5 months ago 12
Swift Question

Execute action of code after certain amount of time in swift

I want an action to be run after 120 seconds but for the rest of the code to continue to run without interruption is there a way to do this in swift? For example

var timer = 0
if timer == 120{
print("time up")
}
//But This code still needs to be able to be run
if buttonPressed == true{
print("pressed")
}

Answer

see http://stackoverflow.com/a/28821805/6496271

let triggerTime = (Int64(NSEC_PER_SEC) * 10) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in self.functionToCall() })

It calls self.functionToCall() after 10 seconds

To make it 120 secs:

let triggerTime = (Int64(NSEC_PER_SEC) * 120)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
    self.functionToCall()
})