如何使用 URLSession 从 url 获取 JSON 数据?

aje*_*rma 5 json ios nsurlsession swift

我正在开发一个 iOS 应用程序,我必须从这个 url获取数据。

我可以看到这个 url 包含 JSON 数据,所以这里我是否需要解析它,我不知道如何获取这个 JSON 数据。

这是我的代码。

import UIKit
import SwiftyJSON

typealias ServiceResponse = (ApiResponseData, NSError?) -> Void

class ApiManager: NSObject {

    var session:URLSession? = nil
    var urlRequest:URLRequest? = nil

    override init(){
        super.init()

        urlRequest = URLRequest(url: URL(string:"https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json")!)
        urlRequest?.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        session = URLSession(configuration: .default)

    }

    func callRestApiToFetchDetails(onCompletion: @escaping ServiceResponse) {
        let task = session?.dataTask(with: urlRequest!, completionHandler: {data, response, error -> Void in
            print("Response = \(data)")

            do {
                let jsonData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary
                // Do Stuff
                print("\(jsonData)")
            } catch {
                // handle error
            print("Error in parsing - \(error)")
            }
        })
        task?.resume()
    }
}
Run Code Online (Sandbox Code Playgroud)

但我在解析时遇到错误。

在此输入图像描述

Ash*_*iya 4

您的网络服务响应是在您必须通过 转换后 String.Encoding.ascii转换为 。String.Encoding.utf8NSDictionary JSONSerialization

尝试一下这个方法是否有效。

  let url = "https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"
    URLSession.shared.dataTask(with: URL(string: url)!) { (data, res, err) in

        if let d = data {
            if let value = String(data: d, encoding: String.Encoding.ascii) {

                if let jsonData = value.data(using: String.Encoding.utf8) {
                    do {
                        let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as! [String: Any]

                        if let arr = json["rows"] as? [[String: Any]] {
                            debugPrint(arr)
                        }

                    } catch {
                        NSLog("ERROR \(error.localizedDescription)")
                    }
                }
            }

        }
        }.resume()
Run Code Online (Sandbox Code Playgroud)

  • 不要在 Swift 中使用 NSDictionary,也不要显式调用 init 方法。 (2认同)