簡體   English   中英

iOS9的后台計時器

[英]Background timer for ios9

我的應用程序中有一個后台進程。 這是代碼:

@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()
}

但是,它僅在iOS10中有效。 有沒有辦法改寫以前的iOS版本?

在ios9或更低版本上沒有基於塊的計時器API。

要么使用方法作為回調而不是塊,要么使用第三方解決方案,例如BlocksKit(有數百個)

Id有一個方法:

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 {

        }

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM