Jamie Bishop Jamie Bishop - 3 months ago 19
JSON Question

Send POST request in Swift from JSON data sent over WebSocket

I am trying to send a POST request in

Swift
2.2 based on a challenge that is sent over a WebSocket. My current code can be found here. In the
respondToChallenge
function, I need to execute the
JSON
sent via the
WebSocket
.

This is what a example challenge looks like:

[{
"meth": "POST",
"host": "https://openpokemap.pw"
"cont": "application/x-www-form-urlencoded"
"user": "Firefox 42...."
"data": "sjdbsjkbd" //Base64 encoded byte array
}]


And I also will need to POST the status code 200 over the "host" that is declared in the JSON.

Thanks, and go easy on me, this is my first post.

Answer

From the JSON response, you can get the host returned pretty easily after serializing it.

do {
    let dict = try NSJSONSerialization.JSONObjectWithData(challenge.dataUsingEncoding(NSUTF8StringEncoding)) as! [String: AnyObject]
    let host = response["host"] as? String
    print("Host: \(host)")
} catch {
    print("JSON error: \(error")
}

From there, you can use NSURLSession to make the POST request.