快速更新循环

时间:2019-10-21 11:22:46

标签: ios swift loops

我在寻找更新方式时遇到了麻烦。我有这个功能:

func pingHost(_ fullURL: String) -> Bool {
        let url = URL(string: fullURL)
        let task = URLSession.shared.dataTask(with: url!) { _, response, _ in
            if let httpResponse = response as? HTTPURLResponse {
                if httpResponse.statusCode == 200 {
                    self.status = true
                } else if httpResponse.statusCode != 200 {
                    self.status = false
                }
            }
        }
        task.resume()
        return self.status
    }

我希望此函数每秒循环一次。我已经在viewDidLoad函数中尝试了while循环。但是,如果我要添加UI,则由于while而无法加载(while循环永远不会结束,因此viewDidLoad永远不会正确执行)。

viewDidLoad:

override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.purple

        statusLabel.translatesAutoresizingMaskIntoConstraints = false

        self.view.addSubview(statusLabel)
        statusLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        statusLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 125).isActive = true
        statusLabel.text = "Status Label"
        statusLabel.textAlignment = .left
        statusLabel.textColor = UIColor.white
        // Do any additional setup after loading the view.
        while true {
            if (self.pingHost("http://example.com") as Bool) != false {
                print("URL is online")
            } else if (self.pingHost("http://example.com") as Bool) != true {
                print("URL doesn't give a response back")
            }
        }
    }

我希望有人能够帮助我解决这个问题。提前致谢!

1 个答案:

答案 0 :(得分:3)

您可以在viewDidLoad中设置一个计时器: 首先将其声明为变量:

var timer: Timer?

然后在viewDidLoad中:

timer = Timer.scheduledTimer(withTimeInterval: 1.0,
                             repeats: true,
                             block: { [weak self] _ in
                                  self?.pingHost("http://example.com")
})