Tho*_*son 17 iphone uiwebview nsurlrequest ios
我希望能够使用我的UIWebView loadRequest方法发送一些额外的标头.
我试过了:
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.reliply.org/tools/requestheaders.php"]];
[req addValue:@"hello" forHTTPHeaderField:@"aHeader"];
[self.theWebView loadRequest:req];
Run Code Online (Sandbox Code Playgroud)
我也试过继承UIWebView和拦截- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType方法.
在那个方法中,我有一个代码块,看起来像这样:
NSMutableURLRequest *newRequest = [request mutableCopy];
for(NSString *key in [customHeaders allKeys]) {
[newRequest setValue:[customHeaders valueForKey:key] forHTTPHeaderField:key];
}
[self loadRequest:newRequest];
Run Code Online (Sandbox Code Playgroud)
但由于某些未知原因,它导致Web视图无法加载任何内容(空白帧)并出现错误消息NSURLErrorCancelled (-999)(所有已知的修复程序都没有为我修复它).
所以我不知道该怎么做.如何发送自定义标头和UIWebView请求?
非常感谢!
Tho*_*son 20
我发现这是向我的UIWebView请求添加标头的方法 - 覆盖此委托方法:
- (BOOL) webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType) navigationType
Run Code Online (Sandbox Code Playgroud)
使用此代码:
BOOL headerIsPresent = [[request allHTTPHeaderFields] objectForKey:@"my custom header"]!=nil;
if(headerIsPresent) return YES;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
NSURL *url = [request URL];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
// set the new headers
for(NSString *key in [self.customHeaders allKeys]){
[request addValue:[self.customHeaders objectForKey:key] forHTTPHeaderField:key];
}
// reload the request
[self loadRequest:request];
});
});
return NO;
Run Code Online (Sandbox Code Playgroud)
托马斯的答案不适用于具有多个iFrame的(大多数)网页.该解决方案将在完整的UIWebView上加载iFrame请求.例如,如果它为Google推荐调用loadRequest.(这是在一些小的iFrame中)的建议.在整个UIWebView上加载,没有别的.