2014-09-01 80 views
13

這裏是我的天真第一遍代碼:如何訪問NSHTTPURLResponse的「Content-Type」標題?

var httpUrlResponse: NSHTTPURLResponse? // = (...get from server...) 
let contentType = httpUrlResponse?.allHeaderFields["Content-Type"] 

我試過這個代碼的各種派生的,但我不斷收到編譯器警告/相關的NSDictionary類型allHeaderFields屬性之間的基本阻抗失配誤差我希望獲得一個字符串或可選的字符串。

只是不知道如何強制類型。

回答

21

你可以做這樣的事情在斯威夫特3如下:

let task = URLSession.shared.dataTask(with: url) { data, response, error in 
    if let httpResponse = response as? HTTPURLResponse, let contentType = httpResponse.allHeaderFields["Content-Type"] as? String { 
     // use contentType here 
    } 
} 
task.resume() 

很顯然,我在這裏從去(response變量)到HTTPURLResponse,並從allHeaderFields獲取數據。如果你已經有了HTTPURLResponse,那麼它更簡單,但希望這可以說明這個想法。

對於Swift 2,請參閱previous revision of this answer

+0

爲什麼在將它轉換爲String之前需要將它轉換爲NSString?不會「像?字符串的工作? – 2014-09-01 23:02:14

+2

@AaronBrager - 順便說一句,如果讓內容類型= ...作爲? NSString爲?字符串'不再需要。我只是在Xcode 6.3.1中進行了測試,現在更簡單的直接轉換爲'String'現在可以正常工作。因此,我從我的答案中刪除了前一種繁瑣的語法。 – Rob 2015-05-11 19:33:54

-2

實際上它應該是那麼容易,因爲這

NSString* contentType = [[(NSHTTPURLResponse*)theResponse allHeaderFields] valueForKey:@"content-type"]; 

NSString* contentType = [[(NSHTTPURLResponse*)theResponse allHeaderFields][@"content-type"]]; 

但問題是,反應可能作爲一個大寫一個或更低的情況下返回鍵的名稱其中一個,而NSDictionary對於密鑰確實區分大小寫,所以您應該對密鑰進行自己的區分大小寫搜索。

NSDictionary* allFields = [[(NSHTTPURLResponse*)theResponse allHeaderFields]; 
NSString* contentType; 
for (NSString* key in allFields.allKeys) { 
    if ([key compare:@"content-type" options:NSCaseInsensitiveSearch] == NSOrderedSame) { 
      // This is it 
      contentType = allFields[key]; 
      break; 
    } 
} 
+1

答案。對不起,我認爲用Swift標記問題,包括Swift示例代碼會有所幫助。另外,我相信查找是不區分大小寫的(根據文檔)。 – Daniel 2014-09-01 20:23:55

+2

HTTP頭字段不區分大小寫,而字典查找區分大小寫,但根據allHeaderFields文檔,幸運的是,「爲了簡化代碼,某些頭字段名稱被標準化爲標準形式」。所以你可以查找'Content-Type'。 – Rob 2014-09-01 22:49:48

+1

@Daniel你應該只在Swift上標記它,上面有一個Objective-C標籤!所以無論如何,如果你不知道如何將其轉換爲Swift,那麼你遇到了很大的麻煩 – 2014-09-02 09:36:29

1

這適用於Xcode 6.1:

let contentType = httpUrlResponse?.allHeaderFields["Content-Type"] as String? 

多次強制轉換不再需要。

而且在Xcode 6.3與1.2斯威夫特,這個工程:

let contentType = httpUrlResponse?.allHeaderFields["Content-Type"] as? String 
+0

第二種說法甚至在1.2之前都有效,但我猜這不是在九月? – Michal 2015-04-30 11:26:51

0

我使用的擴展,URLResponse來簡化這個(SWIFT 3):請求雨燕語言

extension URLResponse { 

    func getHeaderField(key: String) -> String? { 
     if let httpResponse = self as? HTTPURLResponse { 
      if let field = httpResponse.allHeaderFields[key] as? String { 
       return field 
      } 
     } 
     return nil 
    } 
}