J.M J.M - 2 months ago 6
Swift Question

How to cancel an NSTimer after 60 seconds?

I have a button action that sends data to Parse. Once the button is pressed, the title changes to Cancel, when the "Cancel" button is pressed, the data is removed from Parse. I would like to know how to cancel automatically with NSTimer after 60 seconds. I have an array set up too (var isCalling = false)

// Function called by within NSTimer in button action

func refresh(){
self.callButtonTapped(nil)
!isCalling
}

// Within the button action

if error == nil {
//Success
self.isCalling = true
self.callButton.setTitle("Cancel", forState: UIControlState.Normal)
self.timer = NSTimer(timeInterval: 60.0, target: self, selector: #selector (self.refresh), userInfo: nil, repeats: false)
}

Answer

You should use NSTimer.scheduledTimerWithTimeInterval, just replace this line:

self.timer = NSTimer(timeInterval: 60.0, target: self, selector: #selector (self.refresh), userInfo: nil, repeats: false)

with

self.timer = NSTimer.scheduledTimerWithTimeInterval(60.0, target: self, selector:  #selector (self.refresh), userInfo: nil, repeats: false)

Read NSTimer Class Reference if you want to know more about creating timers.

Comments