簡(jiǎn)述
如今很多復(fù)雜的頁(yè)面,為了進(jìn)度俏蛮,選擇了H5頁(yè)面開(kāi)發(fā)撑蚌,所以就必須在oc中嵌套使用H5頁(yè)面,這樣更快的促進(jìn)項(xiàng)目搏屑。但是對(duì)于交互問(wèn)題争涌,自己遇到的一些問(wèn)題記錄一下。
1.webview的創(chuàng)建 實(shí)例化
_webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0,
[UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
_webView.delegate = self;
_webView.backgroundColor = [UIColor grayColor];
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@'http://192.168.1.23:3000/prop/?user_id=37&token=e06a6842be6b1729da0bbd25c78ae896ead061e4']]];
[self.view addSubview:_webView];
2.在H5中點(diǎn)擊不同的位置跳轉(zhuǎn)到不同的oc界面
正常情況下辣恋,我們一般只需要和前端配合商量好亮垫,點(diǎn)擊位置觸發(fā)代理
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
從代理中我們可以拿到 NSString *string = [[request URL]absoluteString]; 接著通過(guò)字符串的判斷 hasfix,加上和前端的商量我們可以通過(guò)url判斷你點(diǎn)擊的位置
if( [path hasPrefix:@"http://gm_app_client/detail_video/"] ){
NSString * pageId = [path substringFromIndex:@"http://gm_app_client/detail_video/".length];
[self showDetailPage:pageId other:1];
}
這樣就能在事件中跳轉(zhuǎn)到我們的OC代碼了伟骨。
3.還有一種情況饮潦,就是前端沒(méi)做一些處理,需要我們配合前端使用js進(jìn)行交互携狭,這時(shí)候就需要用到一個(gè)JSContext
@property (nonatomic,strong)JSContext *context;
在網(wǎng)絡(luò)加載完成之后代理中
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
1. //iOS調(diào)用js
2. //首先創(chuàng)建JSContext 對(duì)象(此處通過(guò)當(dāng)前webView的鍵獲取到j(luò)scontext)
3.JSContext *context=[_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
4.//// 打印異常,由于JS的異常信息是不會(huì)在OC中被直接打印的,所以我們?cè)谶@里添加打印異常信息,
self.context.exceptionHandler =
^(JSContext *context, JSValue *exceptionValue)
{
context.exception = exceptionValue;
NSLog(@"%@", exceptionValue);
};
//js調(diào)用recharge方法時(shí)會(huì)走block回調(diào)
__weak typeof(self) weakSelf = self;
self.context[@"recharge"] = ^(){
NSArray *args = [JSContext currentArguments];
PKRechargeController *rechageVC = [[PKRechargeController alloc]init];
[weakSelf presentViewController:rechageVC animated:YES completion:nil];
NSLog(@"這是一條測(cè)試數(shù)據(jù) 哈哈哈哈....");
};
其中recharge就是網(wǎng)頁(yè)js中添加的方法继蜡,這樣就能實(shí)時(shí)監(jiān)聽(tīng)一樣 只要你在H5中點(diǎn)擊出發(fā)這個(gè)方法 這樣就能完成H5和oc利用js進(jìn)行嵌套的交互
上面是UIWebview情況下的兩種交互,但是iOS8之后出現(xiàn)了WKWebView.
WKWebview
現(xiàn)在伴隨著iOS11的出現(xiàn)暑中,意味著以后最低的適配版本要提升到iOS9壹瘟,最低都iOS8了,這樣UIWebView講會(huì)退出歷史舞臺(tái)鳄逾,會(huì)被WKwebview替代稻轨,本身前者UIWebview就具有嚴(yán)重的內(nèi)存問(wèn)題,而且如果是JS調(diào)用原生的方法雕凹,那么交互方式也是比較麻煩的(H5端要制定特定協(xié)議頭的URL殴俱,在對(duì)應(yīng)代理方法中攔截URL),然后判斷是否符合要求枚抵,最后還要進(jìn)行字符串的截取操作线欲。
下面讓我們一起來(lái)看WKWebview怎么實(shí)現(xiàn)交互的吧(附上關(guān)鍵OC代碼和JS代碼)
1.首先WKWebview的創(chuàng)建
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init]; //WKWebview配置對(duì)象
WKPreferences *preference = [[WKPreferences alloc]init];
config.preferences = preference;
//是否允許與js進(jìn)行交互,默認(rèn)是YES的汽摹,如果設(shè)置為NO李丰,js的代碼就不起作用了
preference.javaScriptEnabled = YES;
WKUserContentController *userContentController = [[WKUserContentController alloc]init]; //交互的重要之點(diǎn)
[userContentController addScriptMessageHandler:self name:@"Share"]; //切記 Share 方法名一定要和H5開(kāi)發(fā)人員協(xié)商定好 self 指當(dāng)前控制器,切記這個(gè)代理要添加 WKScriptMessageHandler 不然會(huì)報(bào)警告
config.userContentController = userContentController; _homeBannerWebView = [[ArtBaseWKWebView alloc]initWithFrame:CGRectMake(0, 64, KSreenWidth, KSreenHeight - 64) configuration:config];
_homeBannerWebView.urlString = self.urlString;
_homeBannerWebView.UIDelegate = self;
_homeBannerWebView.navigationDelegate = self;
_homeBannerWebView.scrollView.showsHorizontalScrollIndicator = NO;
_homeBannerWebView.scrollView.showsVerticalScrollIndicator = NO;
上面是WKWebview的創(chuàng)建和監(jiān)聽(tīng)逼泣,接下來(lái)看看JS端的代碼
<div id="app">
<div onclick="diaoIos()">ios按鈕</div>
<span id="anniu"></span>
<div onclick="diaoAndroid()">安卓按鈕</div>
<span id="anniu2"></span>
</div>
<!-- <script src="node_modules/vue/dist/vue.min.js"></script> -->
<script>
function diaoAndroid() {
var result = window.android.back({title:"測(cè)試標(biāo)題",content:"測(cè)試分享",url:"html://www.baidu.com"});
document.getElementById("anniu2").innerHTML=result;
}
function diaoIos() {
var results2 = window.webkit.messageHandlers.Share.postMessage({title:"測(cè)試標(biāo)題",content:"測(cè)試分享",url:"html://www.baidu.com"});
document.getElementById("anniu").innerHTML=result2;
}
重點(diǎn)是方法中的Share方法名趴泌,這是監(jiān)聽(tīng)交互的方法名
接下來(lái)就是OC端監(jiān)聽(tīng)代理了
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
NSLog(@"------------------");
if ([message.name isEqualToString:@"Share"]) {
NSLog(@"點(diǎn)擊了調(diào)用了舟舒。。");
}
}
當(dāng)然這是監(jiān)聽(tīng)一個(gè)方法嗜憔,但是其實(shí)這里分析起來(lái)秃励,當(dāng)_homeBannerWebView添加了addScriptMessageHandler檢測(cè)時(shí)候可以理解成下面一句代碼:
[self.homeBannerWebView.configuration.userContentController addScriptMessageHandler:self name:@"Share"];
這里控制器強(qiáng)引用了WKWebview,WKWebView強(qiáng)引用了configuration(copy) configuration強(qiáng)引用了userContentController userContentController 強(qiáng)引用了 self (控制器),所以容易導(dǎo)致循環(huán)引用吉捶。導(dǎo)致控制器無(wú)法被釋放夺鲜,所以可以如下處理
// 因此這里要記得移除handlers
[self.homeBannerWebView.configuration.userContentController removeScriptMessageHandlerForName:@"Share"];
這里重點(diǎn)介紹了是在H5中操作跳轉(zhuǎn)原生,但是在原生APP中操作完再回去呢
OC調(diào)用JS
// 將分享結(jié)果返回給js
NSString *resutString = [NSString stringWithFormat:@"shareResult('%@','%@','%@')",title,content,url];
[self.webView evaluateJavaScript:resutString completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"%@----%@",result, error);
}];
如有錯(cuò)誤呐舔,歡迎指點(diǎn)一二