John Doe
John Doe

Reputation: 23

Swift - Unable to create JSON object from NSData

I am making a post request to a server to authenticate a login attempt. If the attempt works, some information is returned from the server in an NSdata block. I want to be able to break that up into json objects so I can parse it easily.

func connectToServerAndGetCookie(username: String, password: String) -> NSString {
    var url = "********"
    var request = HTTPTask()
    var parameters = ["username": username, "password": password]
    var cookies = ""
    request.requestSerializer = JSONRequestSerializer()
    request.POST(url, parameters: parameters, success: {(response: HTTPResponse) in
        if response.responseObject != nil {
            let data = response.responseObject as NSData
            var jsonError: NSError?
            let str = NSString(data: data, encoding: NSUTF8StringEncoding)

 ////////////////// here is where it fails on the nsjsonserialization. the error: 
//////////////////Cannot convert the expression's type 'NSDictionary?' to type 'NilLiteralConvertible'
// but when i remove the ? on the as, I get the error: expression does not conform to type '$T5'

let json2 : NSDictionary = NSJSONSerialization.JSONObjectWithData(str, options: nil, error:&jsonError ) as? NSDictionary

            println(json2)
            // parse cookies here
        }
        },failure: {(error: NSError) in
            println(" error \(error)")
    })
    return cookies
}

I am just trying to break up the NSData block into json objects

Upvotes: 1

Views: 6025

Answers (2)

Sour LeangChhean
Sour LeangChhean

Reputation: 7409

For swift 3 you can try this too:

let jsonData: Data = data
let jsonDict = try! JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary

For example:

print(jsonDict["width"])

Upvotes: 1

rudedude
rudedude

Reputation: 723

Instead of converting your NSData to String, you can use NSData as it is.

import Foundation

var error: NSError?
let jsonData: NSData = response.responseObject

let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary

Upvotes: 5

Related Questions