#import <Foundation/Foundation.h>
#import <JavaScriptCore/JavaScriptCore.h>
@protocol customJavaScriptDelegate <JSExport>
- (void)call:(NSString * )string;
@end
#import "ViewController.h"
#import "customJavaScriptDelegate.h"
@interface ViewController ()<UIWebViewDelegate,customJavaScriptDelegate>
@property (nonatomic,strong)UIWebView * Web;
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColororangeColor];
//获取本地HTML
NSString * htmlPath = [[NSBundlemainBundle]pathForResource:@"test"ofType:@"html"];
NSURL *url=[NSURLfileURLWithPath:htmlPath];
//创建一个UIWebView
self.Web = [[UIWebViewalloc]initWithFrame:CGRectMake(0,150, 400, 300)];
[self.WebloadRequest:[NSURLRequestrequestWithURL:url]];
self.Web.delegate =self;
[self.viewaddSubview:self.Web];
UIButton * button = [[UIButtonalloc ]initWithFrame:CGRectMake(50,550,70,45)];
[button addTarget:selfaction:@selector(buttonTest:)forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"OC调JS·"forState:UIControlStateNormal];
button.backgroundColor = [UIColorredColor];
[self.viewaddSubview:button];
}
- (void)buttonTest:(UIButton *)sender{
//调用JS方法并返回值
NSString * backStr= [self.WebstringByEvaluatingJavaScriptFromString:[NSStringstringWithFormat:@"test4('%@','%@')",@"ABCD",@"EFG"]];
NSLog(@"=============== %@",backStr);
}
//刚要开始加载时调用
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *url=request.URL;
//判断scheme是否是自定义的
if([url.schemeisEqualToString:@"native"])
{
//判断host是什么方法
if([url.hostisEqualToString:@"log"])
{
//将query param拼接起来
NSString *query=url.query;
//分割字符
NSArray *arr=[query componentsSeparatedByString:@"&"];
NSMutableDictionary *dic=[NSMutableDictionarydictionary];
for(NSString *strin arr)
{
NSArray *arrItem=[str componentsSeparatedByString:@"="];
dic[arrItem[0]]=arrItem[1];
}
NSLog(@"输出%@",dic[@"pwd"]);
}
return NO;
}
return YES;
}
//加载完成后调用
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//获取JSContext对象,对应javascript上下文里的window对象
JSContext *context=[webViewvalueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//将本类对象注入JS中 让JS调用call方法
context[@"callOC"] = self;
context[@"log"]=^(NSString * str)
{
NSLog(@"===== %@",str);
};
}
//加载失败后条用
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
NSLog(@"error:%@",error);
}
/**
* 协议方法
*/
- (void)call:(NSString *)param
{
NSLog(@"JS返回的参数param:%@",param);
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end