2015-05-07 77 views
1

至於NSURLConnection.sendSynchronousRequest所需的響應得到allHeaderFields現在需要NSURLResponseNSHTTPURLResponse我不能讓allHeaderFields ..有什麼我可以做嗎?無法從NSURLConnection.sendSynchronousRequest與SWIFT

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版本,我這樣做不再在迅速工程..

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

而不是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` 
}