How to fetch JSON data from a url using URLSession?

故事扮演 提交于 2020-01-04 13:44:32

问题


I am working on an iOS application in which I have to fetch data from this url .

As I can see this url contain JSON data so here should I need to parse it or not I am not getting it how to get this JSON data.

Here is my code.

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()
    }
}

But I am getting error in parsing.


回答1:


You web service response is String.Encoding.ascii that convert into String.Encoding.utf8 after you have to convert through NSDictionary JSONSerialization.

Try this method to work.

  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()


来源:https://stackoverflow.com/questions/47730117/how-to-fetch-json-data-from-a-url-using-urlsession

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!