2014-12-22 69 views
0

我嘗試以下:如何爲在UIWebView中加載的所有請求設置http標頭?

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{ 

    NSLog([request valueForHTTPHeaderField:@"User-Agent"]);  

    if ([[request valueForHTTPHeaderField:@"User-Agent"] isEqualToString:@"CustomName"]) { 
     return YES; 
    } 
    else { 
     NSMutableURLRequest *mutable_request= [request mutableCopy]; 
     [mutable_request setValue:@"CustomName" forHTTPHeaderField:@"User-Agent"]; 
     request = [mutable_request copy]; 
     [self.web loadRequest:request]; 
     return NO; 
    } 
} 

我甚至添加的下列代碼行到viewDidLoad中()方法:

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"CustomName",@"User-Agent", nil]; 
[[NSUserDefaults standardUserDefaults] registerDefaults:dict]; 

然而每當我嘗試加載使用[self.web loadRequest:request]它進入無限循環的請求並且HTTPHeaderField「User-Agent」的值始終打印爲

"Mozilla/5.0 (iPhone; CPU iPhone OS 10_10_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12B411" 

而不是「CustomName」。

+0

原因無限循環是頭沒有被設置爲我想要的價值,所以每次函數正在調用自己並正在進入else塊 –

回答

0
NSLog(@" web url to load : %@",urlToLoad); 
    NSMutableURLRequest *requestObj = [NSMutableURLRequest requestWithURL:urlToLoad]; 
    [requestObj setValue:[NSString stringWithFormat:@"%@ Safari/528.16", [requestObj valueForHTTPHeaderField:@"User-Agent"]] forHTTPHeaderField:@"User_Agent"]; 
    requestObj.timeoutInterval = 120;//Request Timeout interval added for request 
    [requestObj setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];//added for removing cache data of webView 
    [webview loadRequest:requestObj]; 
+0

謝謝,但我認爲它應該是「UserAgent」而不是「User-Agent」,並且在某些情況下,我認爲它工作,如果它是「User_Agent」,不知道爲什麼但它工作 –

0

我找到了答案,我不得不將HTTPHeader「User-Agent」替換爲「UserAgent」。 刪除連字符( - )爲我做了這件事。

添加下面的方法來我AppDelegate.h還曾

+ (void)initialize { 
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:@"CustomName", @"UserAgent", nil]; 
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary]; 

}