如何使用URLSession从URL获取JSON数据? [英] How to fetch JSON data from a url using URLSession?

查看:138
本文介绍了如何使用URLSession从URL获取JSON数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个iOS应用程序,其中必须从此网址获取数据.

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

如我所见,此url包含JSON数据,因此在这里我是否需要解析它,如何获取此JSON数据我不明白.

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.

这是我的代码.

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.

推荐答案

您的Web服务响应是String.Encoding.ascii,可转换为 String.Encoding.utf8之后,您必须进行转换 NSDictionary JSONSerialization.

You web service response is String.Encoding.ascii that convert into String.Encoding.utf8 after you have to convert through 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()

这篇关于如何使用URLSession从URL获取JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆