Perform POST request in Swift

Jake Johnson picture Jake Johnson · Jun 5, 2014 · Viewed 23.1k times · Source

I am trying to do something like this:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];

request.HTTPMethod = @"POST";

NSString *stringData = @"some data";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

This is what I have so far:

var url = NSURL(string: "some url")
var request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"

var dataString = "some data"
var requestBodyData: NSData = dataString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) as NSData

request.HTTPBody = requestBodyData

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

println("sending request...")

connection.start()

However, the var requestBodyData: line throws the first stone with "Cannot convert the expression's type NSData to type NSData"

Anyone care to weigh in?

Answer

Rengers picture Rengers · Jun 5, 2014

stringByAddingPercentEscapesUsingEncoding returns a string instead of an NSData object. According to this answer, you need to use this to convert to an NSData instance:

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