Search code examples
swifttimerswift4grand-central-dispatchdispatch-queue

Swift - Timer with GCD with condition


I use Firebase to upload a file with a progress indicator:

RappleActivityIndicatorView.setProgress(CGFloat(a), textValue: "\(String(a * 100)) %")
print("\(a) %")

I want to implement a condition : if the value of the % (for eg : 23%) is stuck for 15 sec or more, it launch a cancel of the upload.

I was thinking of a GCD Timer :

 DispatchQueue.main.asyncAfter(deadline: .now() + 15) {
        print("We can launch the cancellation of the upload")
    }

But I don't know how to link the condition of the a value not updated during 15 seconds. Any idea ?

Thanks a lot,


Solution

  • Try this:

    var timer: Timer?
    
    // every time you set new percent start new Timer. if in 15 sec it will not reach new percent -> cancellation begins
    func startNewTimer() {
        timer?.invalidate()
        timer = Timer.scheduledTimer(withTimeInterval: 15, repeats: false, block: { (_) in
            // do cancellation
        })
    }