0

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?

Anton Platonov
  • 379
  • 4
  • 15

1 Answers1

2

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 {

        }

    }
}
Daij-Djan
  • 49,552
  • 17
  • 113
  • 135
  • Hello, again. Thanks for you answer. This feels to be the right solution. However, I can't write the working code with a callback. Can you give me more details for my particular case? Thanks – Anton Platonov Feb 16 '17 at 09:19
  • Huge thanks! I've been struggling to make it work. You just gave me the solution! May I ask you what this part means (_:) in #selector? – Anton Platonov Feb 17 '17 at 16:45
  • 1
    @AntonPlatonov sure, that is the name of the argument - In swift, #selector takes the full method signature: `#selector(MyClass.myMethod(myArg1:myArg2:myArg3:)` – Daij-Djan Feb 17 '17 at 20:32