Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post a JSON with new Apple Swift Language

Tags:

json

post

ios

swift

I'm (trying to) learn the Swift's Apple language. I'm at Playground and using Xcode 6 Beta. I'm trying to do a simple JSON Post to a local NodeJS server. I already had googled about it and the major tutorials explain how to do it in a project, not at PLAYGROUND, than don't write stupid thinks like: "google it" or "it's obvious" or "look this link" or never-tested-and-not-functional-code

This is what i'm trying:

var request = NSURLRequest(URL: NSURL(string: "http://localhost:3000"), cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)

var response : NSURLResponse?
var error : NSError?

NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)

I had tried:

var dataString = "some data"

var request = NSMutableURLRequest(URL: NSURL(string: "http://posttestserver.com/post.php"))
request.HTTPMethod = "POST"

let data = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)

var requestBodyData: NSData = data
request.HTTPBody = requestBodyData

var connection = NSURLConnection(request: request, delegate: nil, startImmediately: false)

println("sending request...")
connection.start()

Thank you! :)

like image 215
Thales P Avatar asked Jul 04 '14 03:07

Thales P


2 Answers

Nate's answer was great but I had to change the request.setvalue for it to work on my server

// create the request & response
var request = NSMutableURLRequest(URL: NSURL(string: "http://requestb.in/1ema2pl1"), cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
var response: NSURLResponse?
var error: NSError?

// create some JSON data and configure the request
let jsonString = "json=[{\"str\":\"Hello\",\"num\":1},{\"str\":\"Goodbye\",\"num\":99}]"
request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

// send the request
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)

// look at the response
if let httpResponse = response as? NSHTTPURLResponse {
    println("HTTP response: \(httpResponse.statusCode)")
} else {
    println("No HTTP response")
}
like image 64
Garrett O'Grady Avatar answered Oct 24 '22 16:10

Garrett O'Grady


It looks like you have all the right pieces, just not in quite the right order:

// create the request & response
var request = NSMutableURLRequest(URL: NSURL(string: "http://requestb.in/1ema2pl1"), cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
var response: NSURLResponse?
var error: NSError?

// create some JSON data and configure the request
let jsonString = "json=[{\"str\":\"Hello\",\"num\":1},{\"str\":\"Goodbye\",\"num\":99}]"
request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

// send the request
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)

// look at the response
if let httpResponse = response as? NSHTTPURLResponse {
    println("HTTP response: \(httpResponse.statusCode)")
} else {
    println("No HTTP response")
}
like image 40
Nate Cook Avatar answered Oct 24 '22 16:10

Nate Cook