Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift NSURLConnection sendSynchronousRequest

Tags:

swift

In Objective C the following syntax was possible:

NSHTTPURLResponse *response = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
if ([response statusCode] == 404)
{
}

Now in Swift I have used:

var response : AutoreleasingUnsafeMutablePointer<NSURLResponse?> = nil
let urlData = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: err)

which works, but I cannot access statusCode anymore, because if I use NSHTTPURLResponse it returns an error that NSURLResponse is needed!

Do you know any way to solve this?

like image 664
user3573256 Avatar asked Jan 05 '15 18:01

user3573256


1 Answers

Instead of manually creating an AutoreleasingUnsafeMutablePointer, you can simply use & to wrap the value you want to send a pointer to - your code becomes much simpler:

var response: NSURLResponse?
var error: NSError?
let urlData = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)

After the call, you need to cast your response to NSHTTPURLResponse to access those properties:

if let httpResponse = response as? NSHTTPURLResponse {
    println(httpResponse.statusCode)
}
like image 178
Nate Cook Avatar answered Nov 15 '22 19:11

Nate Cook