iOS webview与Js的交互 以及修改cookie、header头(转载)

第一部分:webview与Js的交互

第二部分:设定cookie

第三部分:修改header头

一.webview与Js的交互

#import"webView.h"#import//系统支持库

@protocolJSObjcDelegate//定义web与JS交互的协议

-(void)goToNextActivity:(NSString*)urlStr;//JS需要调用的方法,参数可有可无,根据需要设定

@end

@interfacewebView()//遵守协议

@property(nonatomic,strong)JSContext * jsContext;//创建JSContext对象 我把它当作上下文对象,用于连接JS和OC

@end

@implementationwebView

-(instancetype)initWithFrame:(CGRect)frame url:(NSURL*)url{

self= [superinitWithFrame:frame];

if(self) {

NSURLRequest*request = [NSURLRequestrequestWithURL:url];

self.delegate=self;

[selfloadRequest:request];

}returnself;

}

-(void)webViewDidFinishLoad:(UIWebView*)webView{

self.jsContext= [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];self.jsContext[@"myObj"] =self;//这里把self赋值给self.jsContext的myObj对象,那么在JS中就可以通过myObj调用oc方法了

self.jsContext.exceptionHandler= ^(JSContext *context, JSValue *exceptionValue) {

context.exception= exceptionValue;NSLog(@"异常信息:%@", exceptionValue);

};

}//webview调用方法-(void)goToNextActivity:(NSString*)urlStr{NSLog(@"goToNextActivity str:%@",urlStr);

}@end

第二部分:设定cookie

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType{NSDictionary*dic = @{@"TOKEN":[DEFAULTS objectForKey:@"token"],@"UID":[DEFAULTS objectForKey:@"userID"]};

[dic enumerateKeysAndObjectsUsingBlock:^(idkey,idobj,BOOL*stop) {// 设定 cookieNSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:

[NSDictionarydictionaryWithObjectsAndKeys:

[request.URLhost], NSHTTPCookieDomain,

[request.URLpath], NSHTTPCookiePath,

key,NSHTTPCookieName,

obj,NSHTTPCookieValue,nil]];

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];//        NSLog(@"cookie = %@",cookie);}];returnYES;

}

第三部分:修改header头

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

NSMutableURLRequest *mutableRequest = [request mutableCopy];

//这里加了一些判断,避免死循环,因为修改完成后webview需要重新加载request (其中DEFAULTS 是NSUserDefaults存了一些后台程序返回的内容)if(!request.allHTTPHeaderFields[@"CITY"]) {

[mutableRequest addValue:[DEFAULTS objectForKey:@"city"] forHTTPHeaderField:@"CITY"];

[self loadRequest:request];

}elseif(![[DEFAULTS objectForKey:@"city"] isEqualToString:request.allHTTPHeaderFields[@"CITY"]]) {

[mutableRequest setValue:[DEFAULTS objectForKey:@"city"] forHTTPHeaderField:@"CITY"];

request = [mutableRequest copy];

[self loadRequest:request];

}returnYES;

}

转载地址:http://blog.csdn.net/create_pro/article/details/60140245

你可能感兴趣的:(iOS webview与Js的交互 以及修改cookie、header头(转载))