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

How to fetch JSON data from a url using URLSession?

我正在开发一个 iOS 应用程序,我必须在其中从 this 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()
    }
}

但是我在解析时遇到错误。

您的 Web 服务响应是 String.Encoding.ascii 转换成 String.Encoding.utf8之后你要转换通过 NSDictionary 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()