Timer.scheduledTimer swift 3兼容iOS 10

roc*_*ift 28 ios swift ios9 ios10 xcode8-beta3

我需要安排一个Timer来每秒触发一个函数,但是我发现在xcode 8 beta 3中,scheduledTimer仅适用于iOS 10.在iOS 9或之前版本中使用计时器有没有其他选择?

Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in print("Hi!")})
Run Code Online (Sandbox Code Playgroud)

roc*_*ift 56

解决了使用

Timer.scheduledTimer(timeInterval: 1,
                           target: self,
                         selector: #selector(self.updateTime),
                         userInfo: nil,
                          repeats: true)
Run Code Online (Sandbox Code Playgroud)


Kri*_*ofe 15

使用swift3运行计时器,

var timer: Timer?

func startTimer() {

    if timer == nil {
        timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(self.loop), userInfo: nil, repeats: true)
    }
}

func stopTimer() {
    if timer != nil {
        timer?.invalidate()
        timer = nil
    }
}

func loop() {
    let liveInfoUrl = URL(string: "http://192.168.1.66/api/cloud/app/liveInfo/7777")
    let task = URLSession.shared.dataTask(with: liveInfoUrl! as URL) {data, response, error in
        guard let data = data, error == nil else { return }
        print(String(data: data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) ?? "aaaa")
    }
    task.resume()
}
Run Code Online (Sandbox Code Playgroud)

不使用时释放计时器.

一旦在运行循环上调度,计时器将以指定的间隔触发,直到它失效.非重复计时器在触发后立即使其自身无效.但是,对于重复计时器,您必须通过调用其invalidate()方法自行使计时器对象无效.


Inc*_*Dev 6

以下是可兼容的示例代码:

 if #available(iOS 10.0, *) {

        Timer.scheduledTimer(withTimeInterval: 15.0, repeats: true){_ in

            // Your code is here:
            self.myMethod()
        }
    }
    else {

        Timer.scheduledTimer(timeInterval: 15.0, target: self, selector: #selector(self.myMethod), userInfo: nil, repeats: true)
    }
Run Code Online (Sandbox Code Playgroud)

//你的方法或功能:

// MARK: -  Method

@objc func myMethod() {

    print("Hi, How are you.")
}
Run Code Online (Sandbox Code Playgroud)