Timer.scheduledTimer Swift 3 pre-iOS 10 兼容性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38695802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:48:16  来源:igfitidea点击:

Timer.scheduledTimer Swift 3 pre-iOS 10 compatibility

iosswiftios9ios10xcode8-beta3

提问by rockdaswift

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.

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

Is there any alternative for using the timer in iOS 9 or previous versions?

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

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

回答by rockdaswift

Solved using

解决了使用

Timer.scheduledTimer(timeInterval: 1,
                           target: self,
                         selector: #selector(self.updateTime),
                         userInfo: nil,
                          repeats: true)

回答by Kris Roofe

Run a timer with swift3,

用 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.

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

回答by Incredible_Dev

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

回答by Kiran jadhav

Updated for swift 3:

为 swift 3 更新:

If you want to use Timer for some delay or any other purpose used below lines of code in your project;

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

// function defination:

// 函数定义:

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...")

}

// function call:

// 函数调用:

self.usedTimerForDelay()

NOTE:- you can change the time interval as you want.

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

//Enjoy coding..!

//享受编码..!

回答by hhamm

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

回答by senlinmu

Timer.scheduledTimer

Put it in the main thread.

把它放在主线程中。

回答by Kike Gamboa

The correct form is:

正确的形式是:

Timer.scheduledTimer(withTimeInterval: 2, repeats: false){_ in
   "Here your code method"
}