Swift URLSession不输出任何数据、响应或错误

1zmg4dgp  于 11个月前  发布在  Swift
关注(0)|答案(1)|浏览(85)

因此,我尝试对指定的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()
yizd12fk

yizd12fk1#

import PlaygroundSupport

let url = URL(string: urlString)!
        var mutableRequest = NSMutableURLRequest(url: url)
        mutableRequest.setValue(key, forHTTPHeaderField: "X-Access-Key")
        
        //this line is necessary
        PlaygroundPage.current.needsIndefiniteExecution = true
        
        let task = URLSession.shared.dataTask(with: mutableRequest as URLRequest, completionHandler: { (data, response, error) in
            //print(mutableRequest)
            //check for error
            if let error = error {
              print("Error accessing swapi.co: /(error)")
              return
            }
        
            //http response result
            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 {
                do {
                //use JSONSerialization
                 let json = try JSONSerialization.jsonObject(with: safeData, options: [])
            
                } catch let error as NSError {
                    print(error)
                }
            }
       PlaygroundPage.current.finishExecution()
       })
        //run the task.
       task.resume()

相关问题