如何向用户显示网站状态码?

How to display website status code to user?

我正在尝试获取网站的状态代码并将其显示给用户。我的代码是:

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

但由于某些原因,它只显示标签的默认文本。

如有任何帮助,我们将不胜感激!

编辑:正如 Donmag 所说,我设置了任务,但我没有 运行 它 (task.resume)。 谢谢!

您设置了 .dataTask,但从未实际执行该代码...

    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()