Search code examples
storyboardswift5http-status-codesurlsession

How to display website status code to user?


Im trying to get the status code of a website and display it to the user. My code is :

override func viewDidLoad() {
        super.viewDidLoad()
        let dataURL = "https://google.com"
        let request = URLRequest(url: URL(string: dataURL)!)
        URLSession.shared.dataTask(with: request) { [self] (data, response, error) in

        let httpResponse = response as? HTTPURLResponse
            let responsecode = httpResponse!.statusCode
            ServerStausLabel.text = String(responsecode)
            
        }
    }

But for some reason it just displays the default text of the label.

Any help would be greatly appreciated!

EDIT: As Donmag said, I set up the task, but I didn't run it(task.resume). Thanks!


Solution

  • You set up the .dataTask, but never actually execute that code...

        let dataURL = "https://google.com"
        let request = URLRequest(url: URL(string: dataURL)!)
        
        let task = URLSession.shared.dataTask(with: request) { [self] (data, response, error) in
    
            // properly unwrap the optional response
            if let httpResponse = response as? HTTPURLResponse {
                let responsecode = httpResponse.statusCode
                ServerStausLabel.text = String(responsecode)
            } else {
                print("Request Failed")
            }
            
        }
        
        // this executes the request
        task.resume()