Меняйте UILabels каждые несколько секунд - PullRequest
0 голосов
/ 11 июня 2019

У меня есть ViewController, который имеет только 2 UILabels, как я могу сделать так, чтобы данные UILabels менялись каждые несколько секунд?Данные поступают из JSON API.Я не знаю, как это все называется.Carousel?Я попробовал поискать в 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 голосов
/ 11 июня 2019

Это можно сделать, либо опросив API, либо если ваш API поддерживает push-уведомления. Подпишитесь на тихое push-уведомление, и вы сможете обновить ярлык.

Использование 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()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...