gpt4 book ai didi

ios - 快速更新循环

转载 作者:行者123 更新时间:2023-11-28 10:27:03 24 4
gpt4 key购买 nike

我在寻找更新某些内容的方法时遇到了一些麻烦。我有这个功能:

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

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

最佳答案

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

var timer: Timer?

然后在viewDidLoad中:

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

关于ios - 快速更新循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58485265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com