Timer.scheduledTimer swift 3 pre iOS 10 compatibil

2019-01-18 01:32发布

I need to schedule a Timer for firing a function every second but I see that in xcode 8 beta 3 the scheduledTimer is only available for iOS 10. Is there any alternative for using the timer in iOS 9 or previous versions?

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

7条回答
啃猪蹄的小仙女
2楼-- · 2019-01-18 02:15

The correct form is:

Timer.scheduledTimer(withTimeInterval: 2, repeats: false){_ in
   "Here your code method"
}
查看更多
Bombasti
3楼-- · 2019-01-18 02:17
Timer.scheduledTimer

Put it in the main thread.

查看更多
戒情不戒烟
4楼-- · 2019-01-18 02:19

Solved using

Timer.scheduledTimer(timeInterval: 1,
                           target: self,
                         selector: #selector(self.updateTime),
                         userInfo: nil,
                          repeats: true)
查看更多
迷人小祖宗
5楼-- · 2019-01-18 02:19

Run a timer with 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()
}

Release the timer when you not use it.

Once scheduled on a run loop, the timer fires at the specified interval until it is invalidated. A nonrepeating timer invalidates itself immediately after it fires. However, for a repeating timer, you must invalidate the timer object yourself by calling its invalidate() method.

查看更多
一纸荒年 Trace。
6楼-- · 2019-01-18 02:23

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.")
}
查看更多
时光不老,我们不散
7楼-- · 2019-01-18 02:27

Swift 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)")
    }
}
查看更多
登录 后发表回答