iosjsonswiftnsdata

Reading Data in API response | iOS


I'm trying to integrate a login API in my iOS project. When I hit that API in browser it gives me correct JSON response. Whereas, when I call it in my app, i'm unable to read JSON. Code is as:

let url = NSURL(string: "myURL")
let request = NSURLRequest(URL: url!)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
        
    if error != nil {
          print (error)
     }
      do {
         //jsonDict is always nil
         if let jsonDict = try self.jsonFromData(data!) {
            print (jsonDict)
         }
       }
       catch {
          print ("hi")
        }    
    }

jsonFromData is as:

private func jsonFromData(jsonData: NSData) throws -> [NSDictionary]?
{
    var jsonDict: [NSDictionary]? = nil
    do
    {
        jsonDict = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments) as? [NSDictionary]
    }
    catch
    {
        throw(error)
    }
    
    return jsonDict
}

Response of API, when hit in browser is as:

enter image description here

Please help me; what I am doing wrong?

UPDATE: I just checked that if i convert data to String, it gives correct value. i.e.

let string = NSString(data: jsonData, encoding: NSASCIIStringEncoding)
print (string)
//OUTPUT: Optional({"Authenticated":true,"CustomerID":000,"CustomerName":"TEMP","Members":[{"MemberID":000,"MemberNumber":"000","MembershipID":00,"MembershipExpiration":"\/Date(1517464799000-0600)\/","ValidBuyerTypes":[0]}]})

Solution

  • Look at your code where you decode the JSON and the as? statement. You are trying to get an array of NSDictionary. Your JSON as printed contains a single dictionary, not an array.