无法使用swift从NSURLConnection.sendSynchronousRequest获取allHeaderFields

时间:2015-05-07 12:34:08

标签: ios objective-c swift

由于NSURLConnection.sendSynchronousRequest所需的响应现在需要NSURLResponse而不是NSHTTPURLResponse我无法获得allHeaderFields ..我能在这做些什么吗?

var newRequest: NSMutableURLRequest = NSMutableURLRequest(URL: request.URL)
newRequest.HTTPMethod = "HEAD"
var response: NSURLResponse
NSURLConnection.sendSynchronousRequest(newRequest, returningResponse: &response, error: nil)
if response.respondsToSelector(Selector(allHeaderFields)) {
    let allHeaders = response.allHeaderFields
}

在旧的Objective-C版本中,我正在做这个,它不再适用于swift ..

NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[request URL]];
[newRequest setHTTPMethod:@"HEAD"];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest:newRequest returningResponse:&response error: NULL];
if ([response respondsToSelector:@selector(allHeaderFields)]) {
    NSDictionary *dictionary = [response allHeaderFields];
}

1 个答案:

答案 0 :(得分:1)

而不是respondsToSelector,您应该使用可选绑定,将其强制转换为NSHTTPURLResponse

let newRequest: NSMutableURLRequest = NSMutableURLRequest(URL: url)
newRequest.HTTPMethod = "HEAD"

var response: NSURLResponse?
NSURLConnection.sendSynchronousRequest(newRequest, returningResponse: &response, error: nil)

if let httpResponse = response as? NSHTTPURLResponse {
    // use `httpResponse.allHeaderFields`
}