因?yàn)轫?xiàng)目需求驅(qū)動(dòng)需求礁叔。折騰了幾天,由于之前沒有UIWebView與JS交互的經(jīng)歷,并且覺得這次寫完之后感覺以后原生的app和js交互會(huì)越來越多润匙,特此留下一點(diǎn)文字,方便日后回顧唉匾。
在這我用兩種方式小談UIWebView與JS交互孕讳,和一種WKWebView和js交互,相關(guān)的項(xiàng)目已上傳github巍膘,有些興趣的可以在后文中下載查看厂财。
首先說一下UIWebView與JS的交互
初始化UIWebView
UIWebView *web = [[UIWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];
1.這是加載網(wǎng)絡(luò)連接的形式
// NSURL *url = [NSURL URLWithString:@"https://baidu.com"];
// NSURLRequest *request = [NSURLRequest //requestWithURL:url];
// [web loadRequest:request];
2.加載本地html
//首先創(chuàng)建webView加載本地的html文件
NSString *path = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"JSCallOC.html"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
[self.webView loadRequest:request];
[self.view addSubview:web];
相關(guān)的代理方法
- (void)webViewDidStartLoad:(UIWebView *)webView{
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
}
方式一
第一種方式是用JS發(fā)起一個(gè)響應(yīng)的URL請(qǐng)求,然后利用UIWebView的代理方法攔截這次請(qǐng)求峡懈,然后再做相應(yīng)的處理璃饱。
我寫了一個(gè)簡(jiǎn)單的HTML網(wǎng)頁和一個(gè)btn點(diǎn)擊事件用來與原生OC交互,HTML代碼如下:
<html>
<!--描述網(wǎng)頁信息-->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>小黃</title>
<style>
.btn{height:40px; width:60%; padding: 0px 30px; background-color: #0071E7; border: solid 1px #0071E7; border-radius:5px; font-size: 1.2em; color: white}
</style>
<script>
function clear(){
document.getElementById('mobile').innerHTML = ''
document.getElementById('name').innerHTML = ''
document.getElementById('msg').innerHTML = ''
}
//提供給OC調(diào)用JS的方法列表
function alertMobile() {
//alert('我是上面的小黃 手機(jī)號(hào)是:13300001111')
document.getElementById('mobile').innerHTML = '我是上面的小黃 手機(jī)號(hào)是:13300001111'
}
function alertName(msg) {
//alert('你好 ' + msg + ', 我也很高興見到你')
document.getElementById('name').innerHTML = '你好 ' + msg + ', 我也很高興見到你'
}
function alertSendMsg(num,msg) {
//alert('這是我的手機(jī)號(hào):' + num + ',' + msg + '!!')
document.getElementById('msg').innerHTML = '這是我的手機(jī)號(hào):' + num + ',' + msg + '!!'
}
//JS調(diào)用oc響應(yīng)方法列表
function btnClick1() {
location.href = "rrcc://showMobile"
}
function btnClick2() {
location.href = "rrcc://showName_?xiaohuang"
}
function btnClick3() {
location.href = "rrcc://showSendNumber_msg_?13300001111&go climbing this weekend"
}
</script>
</head>
<!--網(wǎng)頁具體內(nèi)容-->
<body>
<br/><br/>
<div>
<label>小黃:13300001111</label>
</div>
<br/><br/>
<div id="mobile"></div>
<br/>
<div>
<button class="btn" type="button" onclick="btnClick1()">小紅的手機(jī)號(hào)</button>
</div>
<br/>
<div id="name"></div>
<br/>
<div>
<button class="btn" type="button" onclick="btnClick2()">打電話給小紅</button>
</div>
<br/>
<div id="msg"></div>
<br/>
<div>
<button class="btn" type="button" onclick="btnClick3()">發(fā)短信給小紅</button>
</div>
</body>
</html>
然后在項(xiàng)目的控制器中實(shí)現(xiàn)UIWebView的代理方法:
#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(@"%@",NSStringFromSelector(_cmd));
//OC調(diào)用JS是基于協(xié)議攔截實(shí)現(xiàn)的 下面是相關(guān)操作
NSString *absolutePath = request.URL.absoluteString;
NSString *scheme = @"rrcc://";
if ([absolutePath hasPrefix:scheme]) {
NSString *subPath = [absolutePath substringFromIndex:scheme.length];
if ([subPath containsString:@"?"]) {//1個(gè)或多個(gè)參數(shù)
if ([subPath containsString:@"&"]) {//多個(gè)參數(shù)
NSArray *components = [subPath componentsSeparatedByString:@"?"];
NSString *methodName = [components firstObject];
methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
SEL sel = NSSelectorFromString(methodName);
NSString *parameter = [components lastObject];
NSArray *params = [parameter componentsSeparatedByString:@"&"];
if (params.count == 2) {
if ([self respondsToSelector:sel]) {
[self performSelector:sel withObject:[params firstObject] withObject:[params lastObject]];
}
}
} else {//1個(gè)參數(shù)
NSArray *components = [subPath componentsSeparatedByString:@"?"];
NSString *methodName = [components firstObject];
methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
SEL sel = NSSelectorFromString(methodName);
NSString *parameter = [components lastObject];
if ([self respondsToSelector:sel]) {
[self performSelector:sel withObject:parameter];
}
}
} else {//沒有參數(shù)
NSString *methodName = [subPath stringByReplacingOccurrencesOfString:@"_" withString:@":"];
SEL sel = NSSelectorFromString(methodName);
if ([self respondsToSelector:sel]) {
[self performSelector:sel];
}
}
}
return YES;
}
注意:1. 通過scheme進(jìn)行攔截到我們需要的url做出響應(yīng)的判斷肪康。
2.html中需要設(shè)置編碼荚恶,否則中文參數(shù)可能會(huì)出現(xiàn)編碼問題。
3.JS用直接用document.location的方式,這是一種早期的交互方式磷支,現(xiàn)在oc里面有一個(gè)javascriptcore的框架谒撼,后面在詳解。
早期的JS與原生交互的開源庫很多都是用得這種方式來實(shí)現(xiàn)的齐唆,例如:PhoneGap嗤栓、WebViewJavascriptBridge。關(guān)于這種方式調(diào)用OC方法箍邮,唐巧早期有篇文章有過介紹:關(guān)于UIWebView和PhoneGap的總結(jié)
方式二
在iOS 7之后茉帅,apple添加了一個(gè)新的庫JavaScriptCore,用來做JS交互锭弊,因此JS與原生OC交互也變得簡(jiǎn)單了許多堪澎。
首先導(dǎo)入JavaScriptCore庫, 然后在OC中獲取JS的上下文
- JS調(diào)OC方法
首先導(dǎo)入頭文件
#import <JavaScriptCore/JavaScriptCore.h>
屬性中添加
@property (strong, nonatomic) JSContext *context;
JS調(diào)用OC方法一般在WebView的代理方法中實(shí)現(xiàn)
#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
// 以 html title 設(shè)置 導(dǎo)航欄 title
self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
// 禁用 頁面元素選擇
//[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
// 禁用 長按彈出ActionSheet
//[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
// Undocumented access to UIWebView's JSContext
self.context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
// 打印異常
self.context.exceptionHandler =
^(JSContext *context, JSValue *exceptionValue)
{
context.exception = exceptionValue;
NSLog(@"%@", exceptionValue);
};
// 以 JSExport 協(xié)議關(guān)聯(lián) native 的方法
self.context[@"native"] = self;
// 以 block 形式關(guān)聯(lián) JavaScript function
self.context[@"log"] =
^(NSString *str)
{
NSLog(@"%@", str);
};
// 以 block 形式關(guān)聯(lián) JavaScript function
self.context[@"alert"] =
^(NSString *str)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"msg from js" message:str delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
[alert show];
};
__block typeof(self) weakSelf = self;
self.context[@"addSubView"] =
^(NSString *viewname)
{
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(10, 500, 300, 100)];
view.backgroundColor = [UIColor redColor];
UISwitch *sw = [[UISwitch alloc]init];
[view addSubview:sw];
[weakSelf.view addSubview:view];
};
//多參數(shù)
self.context[@"mutiParams"] =
^(NSString *a,NSString *b,NSString *c)
{
NSLog(@"%@ %@ %@",a,b,c);
};
}
以上只是相關(guān)主要代碼,詳細(xì)的請(qǐng)移步github查看
OC調(diào)JS
- 初始化JSContext
- 加載js文件
- 在oc中創(chuàng)建JSValue代表JS中的對(duì)象,讓JS對(duì)象去執(zhí)行方法
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.title = @"oc call js";
self.context = [[JSContext alloc] init];
[self.context evaluateScript:[self loadJsFile:@"test"]];
}
- (NSString *)loadJsFile:(NSString*)fileName
{
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"js"];
NSString *jsScript = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
return jsScript;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)sendToJS:(id)sender {
NSNumber *inputNumber = [NSNumber numberWithInteger:[self.textField.text integerValue]];
JSValue *function = [self.context objectForKeyedSubscript:@"factorial"];
JSValue *result = [function callWithArguments:@[inputNumber]];
self.showLable.text = [NSString stringWithFormat:@"%@", [result toNumber]];
}
以上是關(guān)于UIWebView和js的交互味滞。
戳這里:本文的DEMO地址歡迎star樱蛤,下載。
戳這里:本文的DEMO地址-JavaScriptCore歡迎star剑鞍,下載昨凡。