user5130344
user5130344

Reputation:

iOS Swift Json Serialization breaking on strings with a return

If I return "test" with/without spaces it works. But when I return a value that a user stored using a return in the string then it fails with a nil error but when I look in the NSLog the value is there....

Code Before Failure

var url:NSURL = NSURL(string:PassURL)!
    var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!

    var postLength:NSString = String( postData.length )

    var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST"
    request.HTTPBody = postData
    request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")


    var reponseError: NSError?
    var response: NSURLResponse?

    var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)

    if ( urlData != nil ) {
        let res = response as! NSHTTPURLResponse!;

        NSLog("Response code: %ld", res.statusCode);

        if (res.statusCode >= 200 && res.statusCode < 300)
        {
            var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

            NSLog("Response ==> %@", responseData);

            var error: NSError?

//FAILS HERE
let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as! NSDictionary

NSLog

2015-07-29 08:52:26.622 testApp[20648:187508] Response ==> {"success":1, "test": "Going to Return Now
Second Line"}
fatal error: unexpectedly found nil while unwrapping an Optional value

But the value is not nil...

NSError

Optional(Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Unescaped control character around character 41.) UserInfo=0x7f9c9942b050 {NSDebugDescription=Unescaped control character around character 41.})

The unescaped character is the return, how can I allow json to accept this?

Upvotes: 0

Views: 1354

Answers (2)

Oxcug
Oxcug

Reputation: 6604

Since you can't post the actual string from the URLRequest, I can't say exactly what's wrong with it. But it sounds like characters no. 24 and 41 are not JSON compliant.

I'd review: json.org. And paste it into: jsonlint.com which'll give you more specifics. And find out why your endpoint is returning invalid JSON.

If you'd like to handle NSJSONSerialization returning nil, simply wrap it in an if let:

if let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as? NSDictionary {
    /* It's a valid JSON object */
} else {
    /* It's not a valid JSON object */
}

Note: Having an array at the root of the json, is not handled by this. If you want to handle that, just expand an else if let as? NSArray. Also, if urlData is nil, this will crash since we're force unwrapping it still.

Upvotes: 1

Kirit Modi
Kirit Modi

Reputation: 23407

var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

OR

var error:NSError? = nil

var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options:nil, error: &error) as? NSDictionary

Upvotes: 1

Related Questions