0

I am new to Swift and API programming and am running into the following error:

uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber length]

This is the line that is causing this error:

print(json[“totalPostsByUser”])

For more context, this is a more complete code sample:

let jsonStr = NSString(data: request.HTTPBody!, encoding: NSUTF8StringEncoding)
let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
   let httpResponse = response as? NSHTTPURLResponse
   var err: NSError?

   if httpResponse!.statusCode == 201 {
      if error == nil {
         let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
         let jsonData: NSData = jsonStr!.dataUsingEncoding(NSUTF8StringEncoding)!
         do {
            if let json: AnyObject = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments) {
               let responseString = NSString(data: data!, encoding:  NSUTF8StringEncoding)
               print(responseString)
               print(json["totalPostsByUser"])
               totalPostsByUser = (json["totalPostsByUser"] as? Int)!
            }
         } catch let parseError {
         }
      }
   }
}
1
  • totalPostsByUser = (json["totalPostsByUser"] as? Int)! should either be totalPostsByUser = json["totalPostsByUser"] as! Int or totalPostsByUser = json["totalPostsByUser"] as? Int (hint, the second option is better) Commented May 25, 2016 at 8:10

1 Answer 1

1

I think you need to replace some piece of code with below code,

if let json: NSMutableDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments) as? NSMutableDictionary
    {
               let responseString = NSString(data: data!, encoding:  NSUTF8StringEncoding)
               print(responseString)
               //print(json["totalPostsByUser"])
               print(json.valueForKey("totalPostsByUser"))
               //totalPostsByUser = (json["totalPostsByUser"] as? Int)!
    }

Convert anyObject to MutableDictionary which will be easy to extract value from key.

Hope this will help you.

Sign up to request clarification or add additional context in comments.

1 Comment

You are welcome :) and please accept this answer so it will be helpful to others also

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.