Anton Platonov
Anton Platonov

Reputation: 389

Background timer for ios9

I have a background process in my app. Here's the code:

@available(iOS 10.0, *)
func startTimer() {
    timer2?.invalidate()
    timer2 = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true, block: { (t) in
        if UIApplication.shared.applicationState == .background {
            NSLog("tic background \(UIApplication.shared.backgroundTimeRemaining)")

            if UIApplication.shared.backgroundTimeRemaining < 10 {

            }

        }

    })
    timer2?.fire()
}

However, it works only in iOS10. Is there a way to rewrite in for previous versions of iOS?

Upvotes: 0

Views: 953

Answers (1)

Daij-Djan
Daij-Djan

Reputation: 50099

there is no block based timer API on ios9 or below.

either use a method as a callback instead of a block OR use a third party solution like e.g. BlocksKit (there are hundreds)

Id go with a method:

func startTimer() {
    timer2?.invalidate()
    timer2 = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(ViewController.timerFired(_:)), userInfo: nil, repeats: true)
    timer2?.fire()
}

@objc
func timerFired(_ timer: Timer) {
    NSLog("tic")

    if UIApplication.shared.applicationState == .background {
        NSLog("tic background \(UIApplication.shared.backgroundTimeRemaining)")

        if UIApplication.shared.backgroundTimeRemaining < 10 {

        }

    }
}

Upvotes: 2

Related Questions