I'm having some trouble with finding a way to update something. I have this function:
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
}
I want this function to loop every second. I already tried a while loop in the viewDidLoad
function. But if I want to add UI it can't load, because of the while (The while loop never ends, so the viewDidLoad is never gonna be executed properly).
The 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")
}
}
}
I hope someone is able to help me with this problem. Thanks in advance!