gpt4 book ai didi

ios - 为什么不能从一个 URL 获得响应?

转载 作者:行者123 更新时间:2023-11-28 11:33:48 26 4
gpt4 key购买 nike

我正在使用 URLSession。我没有收到任何错误或响应。

它适用于一个网址。但是,它不能相互配合。

我也试过 percentencoding。但它也不起作用。

代码如下

let urlString = "https://stark-spire-93433.herokuapp.com/json"//This is not working
//let urlString = "https://jsonplaceholder.typicode.com/todos"//This is working
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)//URLSession.shared
var request = URLRequest(url: URL(string:urlString)!)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONSerialization.data(withJSONObject: [], options: [])
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
print("response---",response)
print("error--",error)
if data != nil {
let json = try? JSONSerialization.jsonObject(with: data!)
print("JSOn",json)

} else {
print("error data is nil")
}

})
task.resume()

最佳答案

代码太繁琐。

这就足够了

let url = URL(string:"https://stark-spire-93433.herokuapp.com/json")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else { print(error!); return }
do {
let json = try JSONSerialization.jsonObject(with: data)
print("JSOn",json)

} catch {
print(error)
}
}
task.resume()

关于ios - 为什么不能从一个 URL 获得响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56142481/

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