我有这个函数来测试发送HTTP请求。
public func test(url: URL) {
print("test")
var request = URLRequest(url: url!)
request.httpMethod = "GET"
let session = URLSession.shared
session.dataTask(with: request) { data, response, err in
print("Entered the completionHandler")
guard err == nil else {
print("error calling GET")
print(err!)
return
}
}.resume()
}
我在测试中运行代码只是为了确保它正在发送请求。
而且它永远不会进入完成 block (输入了completionHandler
从未被打印)。我是 Swift 新手,我错过了什么?
func test_download() {
myClient.test(url: URL(string:"https://www.google.com")!)
print("sleeping...")
sleep(10)
print("done...")
}
最佳答案
看来您没有正确使用闭包。试试这个:
// No need to explicitly set GET method since this is the default one.
let session = URLSession.shared
var request = URLRequest(url: url!)
session.dataTask(with: request) { (data, response, err) in
print("Entered the completionHandler")
guard err == nil else {
print("error calling GET")
return
}
// Do whatever you need to with data and response in here
}.resume()
关于Swift Http 客户端不发送请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45380695/