因此,我尝试对指定的URL(定义为下面的url)进行API调用。我刚开始使用Swift,所以我是这里的新手;我使用URLSession在线学习了一个教程;然而,似乎没有输出任何内容。我添加了print语句来查看打印的内容,但是唯一打印到控制台的是URLSession之外的语句。我的目标是至少先得到一个响应或错误;有什么想法吗?顺便说一句,我正在Playground Swift环境中运行这个脚本,而不是模拟器。
class Script {
struct Content: Codable {
}
func getData(){
print("here first")
let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?appid=03ac0ea03b5fc4cb1f6cf7d57f66f60c&units=metric")
print(url)
let task = URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
print("I'm here")
//check for error
if let error = error {
print("Error accessing swapi.co: /(error)")
return
}
//http response
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode) else {
print("Error with the response, unexpected status code: \(response)")
return
}
print(httpResponse)
//check the data
if let safeData = data {
print("hello")
let decoder = JSONDecoder()
do{
let decodedData = try decoder.decode(Content.self, from: safeData)
print(decodedData)
}catch{
print("error parsing")
}
}
})
print("here 2")
task.resume()
}
}
let script = Script()
script.getPosts()
1条答案
按热度按时间yizd12fk1#