由于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];
}
答案 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`
}