5

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.

enter image description here

7
  • try to print the error in the try catch block } catch (let error) { print("Error in parsing - \(error)") Commented Dec 9, 2017 at 15:32
  • 1
    @lufritz there's no need for the (let error) part, the catch block automatically creates an error variable, so you can just do `catch { print(error)} Commented Dec 9, 2017 at 15:35
  • 1
    Unrelated, but there are several conceptual issues with your code. Don't initialize values as optionals if you will definitely assign a non-optional value to them in the initializer. Moreover, there's no need to assign hardcoded values inside an initializer, this is not Obj-C, in Swift you can assign objects to variables as well outside the initializer. There's also no need to inherit from NSObject, in Swift classes don't need to have a base class. Commented Dec 9, 2017 at 15:39
  • @DávidPásztor I am new in Swift. Can you please help to parse this JSON response. I have updated question. Commented Dec 9, 2017 at 15:44
  • 1
    @ajeetsharma also, if you want to use the SwiftyJSON framework (instead of which I'd recommend using the Codable protocol in Swift 4), why don't you use its methods for decoding the JSON response? Commented Dec 9, 2017 at 16:04

1 Answer 1

4

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()
Sign up to request clarification or add additional context in comments.

5 Comments

It is working, but is there any other simple way we can parse this. Is it possible to more short code for it ?
Don't use NSDictionary in Swift and don't call the init method explicitly.
Also don't use .mutableLeaves as it has no meaning in Swift. You control the mutability using the let or var keywords when declaring the variable.
You can use SwiftyJSON. and my answer is right then right tick mart or up point. thanks.
Must read NSJSONSerialization Fails with Unicode same issues in this apple forums. Seems to be the server side problem. JSON needs to be encoded in UTF-8, but your server seems to be sending it in other encoding

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.