每隔几秒钟更改一次UILabels

时间:2019-06-11 19:33:36

标签: ios json swift

我有一个只有2个UILabel的ViewController,如何使UILabels数据每隔几秒钟更改一次?数据来自JSON API。我不知道这是怎么回事。轮播?我尝试使用Google搜索,但一无所获。基本上是“提示”视图,您可以在其中显示提示,提示每隔几秒钟就会更改一次。

这里是标签和从JSON加载数据的函数

@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var textLabel: UILabel!


func loadJSONData(result: NSDictionary) {
        let JSON = result
        if let title:NSArray = JSON.value(forKeyPath: "ResponseList.$values.Title") as? NSArray {
            if let text:NSArray = JSON.value(forKeyPath: "ResponseList.$values.Text") as? NSArray {
                titleArray = title as! Array<Any>
                textArray = text as! Array<Any>
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

您可以通过轮询API或您的API支持推送通知来执行此操作。订阅静默推送通知,您可以更新标签。

使用GCD和计时器

计时器控件或类-https://gist.github.com/danielgalasko/1da90276f23ea24cb3467c33d2c05768

  class RepeatingTimer {

        let timeInterval: TimeInterval

        init(timeInterval: TimeInterval) {
            self.timeInterval = timeInterval
        }

        private lazy var timer: DispatchSourceTimer = {
            let t = DispatchSource.makeTimerSource()
            t.schedule(deadline: .now() + self.timeInterval, repeating: self.timeInterval)
            t.setEventHandler(handler: { [weak self] in
                self?.eventHandler?()
            })
            return t
        }()

        var eventHandler: (() -> Void)?

        private enum State {
            case suspended
            case resumed
        }

        private var state: State = .suspended

        deinit {
            timer.setEventHandler {}
            timer.cancel()
            /*
             If the timer is suspended, calling cancel without resuming
             triggers a crash. This is documented here https://forums.developer.apple.com/thread/15902
             */
            resume()
            eventHandler = nil
        }

        func resume() {
            if state == .resumed {
                return
            }
            state = .resumed
            timer.resume()
        }

        func suspend() {
            if state == .suspended {
                return
            }
            state = .suspended
            timer.suspend()
        }
    }

    func updateUI(){
        DispatchQueue.global(qos: .background).async { 
            // network call to the API
            DispatchQueue.main.async { 
               // Update the UI Label here
            }
         }
    }

//Usage with Timer 

     let t = RepeatingTimer(timeInterval: 3)
            t.eventHandler = {
                updateUI()
            }
            t.resume()