zzheads zzheads - 2 months ago 43
Swift Question

How insert alert after some time in Swift 3.0

My application asks user question and get answer, each question has some constant time (for example 30 seconds) for answering. I want show user alert something like "Last (n) seconds..." and if user will not answer in that time - app should skips question.
Wrote some code, using DispatchQueue:

let timePerQuestion = 20
let timeStartAlert = 10

for i in (0..<timeStartAlert) {
DispatchQueue.main.asyncAfter(deadline: (.now() + .seconds(timePerQuestion-timeStartAlert+i))) {
self.failureLabel.text = "Left \(Int(timeStartAlert-i)) seconds..."
self.failureLabel.isHidden = false
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(timePerQuestion)) {
self.failureLabel.text = "Reseting question"
self.failureLabel.isHidden = false
self.failureLabel.text = "Sorry, that's not it."

It works, but those code executes even if user answered question in time.
So how I can "reset" or "clear" DispatchQueue.main for prevent executing this code if user answered in time?


well you have to use scheduled Timer from class NStimer

the implementations are as follows:

you need to define a timer:

var timer = Timer()//NStimer()in older versions of swift

timer = scheduledTimer(timeInterval: TimeInterval, invocation: NSInvocation, repeats: Bool)

in which the timeInterval is the period before the execution of the required function,invocationis the function you want to run, and repeatwill repeatedly invoke the function until invalidated.

you can read more about NS timers in https://developer.apple.com/reference/foundation/timer

I hope it helps