Trouble unwrapping JSON Array to a String Value

361 Views Asked by At

I have been struggling with JSON for a few days. I am trying to create a POST request to my web server for a username, that will return information on said user. I have managed to get the JSON response two ways, but I cannot cast any of the elements of the Array to a string. I am using the SWIFTYJSON API too.

import UIKit
import Foundation

class ViewController: UIViewController {

    var token = "barrymanilow"
    var endPoint = "http://www.never.money/simple_app7.php"


@IBOutlet weak var firstLabel: UILabel!

override func viewDidLoad() {
    submitAction(self)
}

func submitAction(sender: AnyObject) {

    let myUrl = NSURL(string: "http://www.mindyour.money/simple_app7.php");
    let request = NSMutableURLRequest(URL:myUrl!);
    request.HTTPMethod = "POST";

    // Compose a query string
    let postString = "token=\(token)";

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
        data, response, error in

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

        // Print out response body
        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("responseString = \(responseString)")

        //Let's convert response sent from a server side script to a NSDictionary object:

        var err: NSError?
        var myJSON = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error:&err) as? NSArray

var json : JSON = JSON(data: data)

        let results: AnyObject? = myJSON?.valueForKey("player_username")
        println("\(results)")
let result2 = json["player_username"].string


    }

    task.resume()
}
}

However, this doesn't seem to be working, can anybody help me?

1

There are 1 best solutions below

0
On BEST ANSWER

I see that when using NSJSONSerialization you're casting your JSON response as an NSArray, so for example to get the first item's player_username with SwiftyJSON you would do:

let result2 = json[0]["player_username"].string

It should work without casting json[0] to a dictionary first because thanks to SwiftyJSON the compiler knows that json[0] is a dictionary.

If for some reason json[0] is not automatically subscriptable, you can do:

let playerOneDic = json[0].dictionary
let result2 = playerOneDic["player_username"].string

Otherwise, without SwiftyJSON, you would have to do something like this:

if let playerOne = myJSON?[0] as? [String:AnyObject] {
    if let username = playerOne["player_username"] as? String {
        println(username)
    }
}