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?
I see that when using
NSJSONSerialization
you're casting your JSON response as an NSArray, so for example to get the first item'splayer_username
with SwiftyJSON you would do:It should work without casting
json[0]
to a dictionary first because thanks to SwiftyJSON the compiler knows thatjson[0]
is a dictionary.If for some reason
json[0]
is not automatically subscriptable, you can do:Otherwise, without SwiftyJSON, you would have to do something like this: