ios - Trouble unwrapping JSON Array to a String Value -
i have been struggling json few days. trying create post request web server username, return information on said user. have managed json response 2 ways, cannot cast of elements of array string. using 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 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 server side script 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, doesn't seem working, can me?
i see when using nsjsonserialization
you're casting json response nsarray, example first item's player_username
swiftyjson do:
let result2 = json[0]["player_username"].string
it should work without casting json[0]
dictionary first because swiftyjson compiler knows json[0]
dictionary.
if reason json[0]
not automatically subscriptable, can do:
let playeronedic = json[0].dictionary let result2 = playeronedic["player_username"].string
otherwise, without swiftyjson, have this:
if let playerone = myjson?[0] as? [string:anyobject] { if let username = playerone["player_username"] as? string { println(username) } }
Comments
Post a Comment