Swift NSURLConnection sendSynchronousRequest

i0S Swift Issue

Question or problem in the Swift programming language:

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 = 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?

How to solve the problem:

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)
}

Hope this helps!