在Swift中使用Accuweather API

时间:2018-03-10 17:28:43

标签: json swift

我已经注册了一个accuweather开发者帐户并且有一个apikey 如何在swift中调用accuweather api,如何解释结果,我回来了?

let citySearchURL = "https://dataservice.accuweather.com/locations/v1/cities/search?apikey=my_api_key&q=my_location_query"     
let url : URL = URL(string: citySearchURL)!
    var request = URLRequest(url: url)

    let task = URLSession.shared.dataTask(with: request) { (data : Data?, response : URLResponse?, error: Error?) in
        if let data = data {
            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] {
                    print(json)
                }
            } catch {
                print(error.localizedDescription)
            }
        }
    }

    task.resume()

这是我目前的一段代码。它没有给我控制台的输出,这意味着JSON序列化无法正常工作。我做错了什么? 以下是数据,响应和错误的内容:

data:936 bytes
response:<NSHTTPURLResponse: 0x600000036520>
下面是一些json,但stackoverflow不能将其识别为代码/引号...

链接到api参考:Accuweather API

1 个答案:

答案 0 :(得分:1)

data:936 bytes表示您收到936字节的API响应,因此没有问题。

问题是您无法将data解析为对象,在您的JSONSerialization语句中,您添加[String:Any]作为可选类型但响应不属于此类型,这就是print语句无法执行的方式。

    let citySearchURL = "https://dataservice.accuweather.com/locations/v1/cities/search?apikey=my_api_key&q=my_location_query"     
    let url : URL = URL(string: citySearchURL)!
    let request = URLRequest(url: url)
    let task = URLSession.shared.dataTask(with: request) { (data : Data?, response : URLResponse?, error: Error?) in
        if let data = data {
            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [Any]{
                    print(json)
                }
           } catch {
                print(error.localizedDescription)
            }
        }
    }
    task.resume()