2015-05-11 101 views
0

出於某種原因,我無法從快捷鍵所需的字典中的鍵中獲取正確的值。這在目標c中起作用。無法從allHeaderFields字典中獲取值

var newRequest: NSMutableURLRequest = NSMutableURLRequest(URL: navigationAction.request.URL!) 
newRequest.HTTPMethod = "HEAD" 
var response: NSURLResponse? 
var filename: AnyObject? 
var filetype: AnyObject? 
NSURLConnection.sendSynchronousRequest(newRequest, returningResponse: &response, error: nil) 
if let httpResponse = response as? NSHTTPURLResponse { 
    let allHeaders = httpResponse.allHeaderFields 
    filename = allHeaders["sfn-Document-Filename"] 
    let typeString: AnyObject? = allHeaders["Content-Type"] 
    let typeArray: Array = typeString!.componentsSeparatedByString("/") 
    filetype = typeArray[1] 
} 

本字典對象看起來像這樣allHeaders [NSObject : AnyObject] 6 key/value pairs

這裏的目標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]; 
    filename = [[response allHeaderFields] objectForKey:@"sfn-Document-Filename"]; 
    NSString *typeString = [dictionary objectForKey:@"Content-Type"]; 
    NSArray *typeArray = [typeString componentsSeparatedByString:@"/"]; 
    filetype = [typeArray objectAtIndex:1]; 
} 

它並不需要做的方式與obj-C一樣,它只是這個工作,它似乎是一個良好的開端。

我得到的文件名的值是filename = (AnyObject?) Some

我試圖將其更改爲:

var filename: String? 
filename = allHeaders["sfn-Document-Filename"] as? String 

但現在我得到一個零字符串和Thread 1: EXC_BAD_ACCESS (code=1, address=0x20)

+0

得到任何錯誤? –

+1

「我無法從字典中獲得正確的值」:這是否意味着您得到錯誤的值?或者根本沒有價值? – Moritz

+0

@EricD。我得到'filename =(AnyObject?)一些' –

回答

0

的原因這一切正在發生是因爲字典中的鍵的值看起來是NSString,並且它找不到String(我認爲它們應該是可以互換的)。

無論哪種方式。這樣做的工作:

var newRequest: NSMutableURLRequest = NSMutableURLRequest(URL: request.URL!) 
newRequest.HTTPMethod = "HEAD" 
var response: NSURLResponse? 
NSURLConnection.sendSynchronousRequest(newRequest, returningResponse: &response, error: nil) 
var filename: NSString? 
var filetype: String? 
if let httpResponse = response as? NSHTTPURLResponse { 
    let headerString = "sfn-Document-Filename" 
    let headerNSString: NSString = (headerString as NSString) 
    let filetypeString = "Content-Type" 
    let filetypeNSString: NSString = (filetypeString as NSString) 

    var allHeaders = httpResponse.allHeaderFields 

    filename = allHeaders[headerNSString] as? NSString 

    let typeString = allHeaders[filetypeNSString] as? NSString 
    let typeArray = typeString!.componentsSeparatedByString("/") 
    filetype = typeArray[1] 
} 

現在我只需要弄清楚爲什麼componentsSeparatedByString是不工作...