Loc Dai Le
Loc Dai Le

Reputation: 1697

Get value out from JSON in Swift xcode 6

I have a JSON file which i converted to a NSDictionary object. My question is how do i get one single value out from this object? I make a httppost to my webside and then i get an JSON array back with to values "success" ,"userId" and "token i want to check on the "access_token" string in "token"

public class HttpPost{

var URLstring : String = "http://95.85.53.176/nhi/api/app/login"
var ClientSecret : String = "SqzssXGU0C5ukzgvivVTeg7QdlZcnBUKULECgkFp"

public func HttpPostToLogin(Email: String, Password: String, completionHandler: (responseSuccess: Int32) -> ())
{

    var postString = "email=" + Email + "&password=" + Password + "&client_secret=" + ClientSecret

    //Declare URL
    var url: NSURL! = NSURL(string: URLstring)
    var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    //Declare which HTTPMethod
    request.HTTPMethod = "POST"

    //POST data
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

    //new thread for receiving data
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
        data, response, error in

        if error != nil
        {
            println("error=\(error)")
            return
        }

        //Check if there is response from server
        println("response =\(response)")

        var responseString = NSString(data: data, encoding: NSUTF8StringEncoding)


        println("responseString =\(responseString)")


        var error: NSError?

        //parse JSON file
        var myJSON : NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &error) as! NSDictionary

        println(myJSON)

        //this works
        var success = myJSON["success"]!.intValue

        //Tried - gives me an error
        //var accessToken = myJSON["token"]["access_token"]!.stringValue

        //println(accessToken)

        //complete task and return success value
        completionHandler(responseSuccess: success!)



    }


    task.resume()

}
}

output:

{
success = 1;
token =     {
    "access_token" = p9f9ge3Fe1dn5T7xpfBZHfZaA7CwYe9fbLNgeqOY;
    "expires_in" = 604800;
    "refresh_token" = w0qltq4SDax5KtIKEEFZm76CsB9BfozsuSrGuRcI;
    "token_type" = Bearer;
};
userId = 61;
}

Upvotes: 0

Views: 1590

Answers (2)

Bhupendra Singh
Bhupendra Singh

Reputation: 121

You should check token is not nil before accessing its value. Otherwise app will crash. Following code will execute when token is not nil and myJSON["token"] is type of NSDictionary.

if let tokenDict = myJSON["token"] as? NSDictionary {
    var accessToken : String? = tokenDict["access_token"] as? String
    var expires_in  : Int? = tokenDict["expires_in"] as? Int
}

Upvotes: 1

Sohel L.
Sohel L.

Reputation: 9540

Try to cast value as String

var tokenDict: NSDictionary = myJSON["token"] as! NSDictionary
var accessToken: String = tokenDict["access_token"] as! String

For UserID:

var myUserID: Int = myJSON["userId"] as! Int

Upvotes: 1

Related Questions