gpt4 book ai didi

Swift Http 客户端不发送请求

转载 作者:行者123 更新时间:2023-11-30 12:16:28 24 4
gpt4 key购买 nike

我有这个函数来测试发送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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com