2010-01-19 70 views

回答

3

您可以使用allHeaderFields方法將它們讀入NSDictionary。

NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; 
    NSDictionary *httpResponseHeaderFields = [httpResponse 
allHeaderFields]; 

是100%安全的,你不會想和

if ([response respondsToSelector:@selector(allHeaderFields)]) {... } 
+0

這不是返回一個NSDictionary而不是一個NSMutableDictionary? – 2010-01-19 20:15:20

+0

是的,這就是代碼示例中的內容。以下是課程參考資料http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSHTTPURLResponse_Class/Reference/Reference.html#//apple_ref/occ/instm/NSHTTPURLResponse/allHeaderFields – shawnwall 2010-01-19 20:30:03

+0

I don看不到不可改變的字典將如何幫助我修改鍵/值 – 2010-01-19 20:34:46

9

我只是說這與一個朋友把它包起來。我的建議是寫一個NSURLResponse的子類。沿着這些路線的東西:

@interface MyHTTPURLResponse : NSURLResponse { NSDictionary *myDict; } 
- (void)setAllHeaderFields:(NSDictionary *)dictionary; 
@end 

@implementation MyHTTPURLResponse 
- (NSDictionary *)allHeaderFields { return myDict ?: [super allHeaderFields]; } 
- (void)setAllHeaderFields:(NSDictionary *)dict { if (myDict != dict) { [myDict release]; myDict = [dict retain]; } } 
@end 

如果你正在處理一個對象,你沒有做,你可以嘗試使用object_setClass到調酒類的。但是我不知道這是否會添加必要的實例變量。你也可以使用objc_setAssociatedObject,如果你能支持一個足夠新的SDK,那麼你可以把它全部放在一個類別中。

1

我有一個類似的問題。我想修改http url響應的頭文件。我需要它,因爲我想爲UIWebView提供緩存的url響應,並且想欺騙Web視圖,即響應未過期(即,我想更改標題的「Cache-Control」屬性,但保留標題的其餘部分)。我的解決方案是使用NSKeyedArchiver對原始http響應進行編碼,並使用委託攔截序列化。在

-(id) archiver:(NSKeyedArchiver*) archiver willEncodeObject:(id) object 

我檢查,如果對象是NSDictionary中,如果是,我回來改性字典(即更新爲「緩存控制」報頭)。之後我使用NSKeyedUnarchiver對序列化的響應進行反序列化。當然,您可以掛鉤到解析器並修改其委託中的標題。

注意,在iOS 5中蘋果公司已經加入

-(id)initWithURL:(NSURL*) url statusCode:(NSInteger) statusCode HTTPVersion:(NSString*) HTTPVersion headerFields:(NSDictionary*) headerFields 

這是不是在文檔(文檔錯誤),但它是NSHTTPURLResponse

的公共API中
0

你能做到這一點,你'd需要NSHTTPURLResponse而不是NSURLResponse,因爲在Swift中,NSURLResponse可以與許多協議一起使用,而不僅僅用於http,如ftpdata:https。因此,您可以調用它來獲取元數據信息,例如預期的內容類型,MIME類型和文本編碼,而NSHTTURLResponse是負責處理HTTP協議響應的人員。因此,它是操縱標題的人。

這是一個小代碼,它處理響應中的標題密鑰Server,並在更改前後輸出值。

let url = "https://www.google.com" 
    let request = NSMutableURLRequest(URL: NSURL(string: url)!) 
    let session = NSURLSession.sharedSession() 
    let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in 

     if let response = response { 

      let nsHTTPURLResponse = response as! NSHTTPURLResponse 
      var headers = nsHTTPURLResponse.allHeaderFields 
      print ("The value of the Server header before is: \(headers["Server"]!)") 
      headers["Server"] = "whatever goes here" 
      print ("The value of the Server header after is: \(headers["Server"]!)") 

     } 

     }) 
     task.resume()