简体   繁体   中英

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:

在此处输入图片说明

Please help me, what i am doing wrong. Thanks.

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

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

This looks right to me. The only thing I can think is that (despite what the string output looks like) the top level container of your response is NOT an NSDictionary . In your jsonFromData function, instead of assuming the result of JSONObjecWithData will be an NSDictionary , I would say:

let iDunnoWhatThisIs = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments) // don't cast this to NSDictionary

and see what you get back. It should either be a dictionary or an array, however, since you have NSJSONReadingOptions.AllowFragments set for the options, it's possible that it could be something else entirely. Start with making SURE you're actually getting back what you're assuming you are and go from there.

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.

尝试改用NSKeyedUnarchiver:

jsonDict = NSKeyedUnarchiver.unarchiveObjectWithData(jsonData)! as NSDictionary

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM