Swift NSURLConnection sendSynchronousRequest

时间:2015-01-05 18:00:26

标签: swift

在Objective C中,可以使用以下语法:

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

现在我在Swift中使用过:

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

有效,但我不能再访问statusCode,因为如果我使用NSHTTPURLResponse,它会返回一个需要NSURLResponse的错误!

你知道怎么解决这个问题吗?

1 个答案:

答案 0 :(得分:26)

您可以简单地使用AutoreleasingUnsafeMutablePointer来包装要发送指针的值,而不是手动创建& - 您的代码变得更加简单:

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

通话结束后,您需要将回复转发给NSHTTPURLResponse以访问这些属性:

if let httpResponse = response as? NSHTTPURLResponse {
    println(httpResponse.statusCode)
}