1、在UIWebviewDelegate的方法中拦截request,设置request的请求头,废话不多说看代码:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSString *urlString = [[request URL] absoluteString];
NSLog(@"==> %@",urlString);
NSMutableURLRequest *mutableRequest = [request mutableCopy];
NSDictionary *requestHeaders = request.allHTTPHeaderFields;
// 判断请求头是否已包含,如果不判断该字段会导致webview加载时死循环
if (requestHeaders[@"token"] && requestHeaders[@"clienttype"]) {
return YES;
} else {
[mutableRequest setValue:@"token" forHTTPHeaderField:@"token"];
[mutableRequest setValue:@"ios" forHTTPHeaderField:@"clienttype"];
request = [mutableRequest copy];
[webView loadRequest:request];
return NO;
}
return YES;
}
经过本人亲测,这样做有一定问题,当在webview执行goBack方法时导致两个界面相互加载的情况,导致死循环加载无法返回,解决方法请参考以下更牛逼的方法2
2、写一个类继承NSURLProtocol,在 + (BOOL)canInitWithRequest:(NSURLRequest *)request 方法拦截request为request添加请求头,这样所有的webview操作请求都会调到这里,为request添加请求头,而且不影响webview的goBack方法返回
#import <Foundation/Foundation.h>
@interface KJURLProtocol : NSURLProtocol
@end
#import "KJURLProtocol.h"
@implementation KJURLProtocol
+ (void)load {
[NSURLProtocol registerClass:self];
}
+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
if ([request isKindOfClass:[NSMutableURLRequest class]]) {
[(id)request setValue:@"ios" forHTTPHeaderField:@"clienttype"];
[(id)request setValue:[KJAppData instance].token forHTTPHeaderField:@"token"];
}
return NO;
}
@end
/********************************************************************************/
+ (BOOL)canInitWithRequest:(NSURLRequest *)request //在此方法决定是否拦截请求,return yes为拦截
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request //在此方法修改请求并返回
- (void)startLoading //执行特定的request请求
- (void)stopLoading //中断特定的request请求
/********************************************************************************/
附:iOS8一会苹果推出一个加载网页视图更吊的框架WebKit,其中的WKWebView 基本包含了UIWebview的所有东西,据说在性能方面优化的不是一点点,并添加了很多主流的东西,例如:实现网页之间的侧滑返回,估算网页的加载进度,如果你的应用已经最低支持iOS8,你还在由于什么,赶快尝试吧。
详解参考:http://www.tuicool.com/articles/FJ3Ave7
wkwebview问题: http://www.cnblogs.com/NSong/p/6489802.html
NSURLProtocol监听 wkwebview请求 解决办法:http://www.tuicool.com/articles/J7ZRF3i