1. #import
2.
3. @property(nonatomic,strong)UIWebView *webView;
@property(nonatomic,strong)JSContext *context;
4. 在网页开始加载的时候,给web返回一个NSString的方法
-(void)webViewDidStartLoad:(UIWebView *)webView
{
//获取js的运行环境
_context =[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
__weak typeof(self)weakSelf = self;
_context[@"returnPosDicct"]= ^(){
NSString *str =[NSString stringWithFormat:@"lat=%@&lng=%@&workCity=%@",weakSelf.posDict[@"lat"],weakSelf.posDict[@"lng"],g_strCurrentCity];
return str;
};
}
5.
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
MyLog(@"%@",error);// 网页加载失败的log
}
6. JS调用OC的方法,JumpToPosition 是JS的方法名,并且传参到app中,赋给OC,OC方法名是JumpToPosition:,参数是args。
//网页加载完成调用此方法
- (void)webViewDidFinishLoad:(UIWebView*)webView
{
__weaktypeof(self) weakSelf =self;
_context[@"JumpToPosition"] = ^(){
NSArray*args = [JSContext currentArguments];
[weakSelf JumpToPosition:args];
};
}
7. //OC调用JS ,JS方法名:change_share()
- (void)OCCallJS {
[_webViewstringByEvaluatingJavaScriptFromString:@"change_share()"];
}