32

我需要安排一个计时器来每秒触发一个功能,但我看到在 Xcode 8 beta 3 中,scheduledTimer 仅适用于 iOS 10。

在 iOS 9 或以前的版本中使用计时器有什么替代方法吗?

Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) in print("Hi!")})
4

8 回答 8

57

使用解决

Timer.scheduledTimer(timeInterval: 1,
                           target: self,
                         selector: #selector(self.updateTime),
                         userInfo: nil,
                          repeats: true)
于 2016-08-01T10:05:07.703 回答
17

使用 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()
}

不使用时释放计时器。

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

于 2017-05-16T06:06:37.700 回答
7

Here is sample code workable with compatibility:

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

//Your method or function:

// MARK: -  Method

@objc func myMethod() {
    print("Hi, How are you.")
}
于 2018-03-01T10:56:54.067 回答
3

为 swift 3 更新:

如果您想将 Timer 用于某些延迟或在项目中的代码行下方使用的任何其他目的;

// 函数定义:

func usedTimerForDelay()  {
    Timer.scheduledTimer(timeInterval: 0.3,
                         target: self,
                         selector: #selector(self.run(_:)),
                         userInfo: nil, 
                         repeats: false)
}

func run(_ timer: AnyObject) {
      print("Do your remaining stuff here...")

}

// 函数调用:

self.usedTimerForDelay()

注意:- 您可以根据需要更改时间间隔。

//享受编码..!

于 2017-09-27T05:50:04.190 回答
3

斯威夫特 3

func runCode(in timeInterval:TimeInterval, _ code:@escaping ()->(Void))
{
    DispatchQueue.main.asyncAfter(
        deadline: .now() + timeInterval,
        execute: code)
}

func runCode(at date:Date, _ code:@escaping ()->(Void))
{
    let timeInterval = date.timeIntervalSinceNow
    runCode(in: timeInterval, code)
}

func test()
{
    runCode(at: Date(timeIntervalSinceNow:2))
    {
        print("Hello")
    }

    runCode(in: 3.0)
    {
        print("World)")
    }
}
于 2017-02-03T22:58:31.913 回答
1

您可以使用以下简单的 shim 为 pre-iOS 10 提供新的基于块的计时器:

class TimerShim {
    private var timer: Timer?
    private let block: (Timer) -> Void

    private init(timeInterval interval: TimeInterval, repeats: Bool, block: @escaping (Timer) -> Void) {
        self.block = block
        timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(timerDidFire), userInfo: nil, repeats: repeats)
    }

    class func scheduledTimer(withTimeInterval interval: TimeInterval, repeats: Bool, block: @escaping (Timer) -> Void) -> Timer {
        return TimerShim(timeInterval: interval, repeats: repeats, block: block).timer!
    }

    @objc private func timerDidFire() {
        block(timer!)
    }
}

使用示例:

TimerShim.scheduledTimer(withTimeInterval: 5, repeats: false) { _ in
    print("boom!")
}
于 2020-06-02T10:48:49.037 回答
1
Timer.scheduledTimer

把它放在主线程中。

于 2018-05-12T09:03:33.693 回答
-5

正确的形式是:

Timer.scheduledTimer(withTimeInterval: 2, repeats: false){_ in
   "Here your code method"
}
于 2017-01-27T23:56:48.960 回答