提问人:CreativeDifference 提问时间:12/14/2021 最后编辑:CreativeDifference 更新时间:1/30/2022 访问量:37
如何向用户显示网站状态码?
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
答:
1赞
DonMag
12/16/2021
#1
您设置了 ,但从未实际执行过该代码....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()
评论
0赞
CreativeDifference
12/19/2021
谢谢!问候亚历山大
上一个:在最后出现斜杠时拆分字符串
下一个:我可以将控制台输出镜像到网站吗?
评论