進(jìn)入15年以后利花,在我們天朝越來越流行混編!尤其是騰訊的 變態(tài)APP微信小程序一出盒揉,撐起了混編的半邊天晋被! 廢話不多說,現(xiàn)在的你應(yīng)該懂得H5技術(shù)了刚盈,就算不懂得羡洛,最起碼的交互應(yīng)該懂得的!這幾天研究了一下 iOS原生與JS交互技術(shù)藕漱,一點(diǎn)心得欲侮,寫下來與大家共同分享!
一肋联、UIWebView :OC與JS交互
1威蕉、OC調(diào)用JS
NSLog(@"OC調(diào)用JS 傳參數(shù) !橄仍!");
/*OC調(diào)用JS篇
方式一 ?無參數(shù) ?通過webView自帶的方法來執(zhí)行JS
*/
//@"OCToJSWithNil('')"這個就是OC讓JS執(zhí)行的Js代碼韧涨,我們要執(zhí)行JS方法,前提JS中的方法名你得知道侮繁,這樣你就可以把JS方法使用拼成字符串虑粥,然后使用webView自帶stringByEvaluatingJavaScriptFromString來執(zhí)行JS代碼的方法來執(zhí)行JS方法
NSString *jsStr = [NSString stringWithFormat:@"OCToJSWithNil('')"];//[NSString stringWithFormat:@"showAlert('%@')",@"這里是JS中alert彈出的message"];
[_webView stringByEvaluatingJavaScriptFromString:jsStr];
//注意:該方法會同步返回一個字符串,因此是一個同步方法宪哩,可能會阻塞UI娩贷。
/*方式二? 通過 JavaScriptCore 來執(zhí)行JS
繼續(xù)使用JavaScriptCore庫來做JS交互。
*/
//必須先獲取JS上下文锁孟,找到要執(zhí)行的JS中的方法名彬祖,利用evaluateScript執(zhí)行JS
//JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
NSString *textJS = @"OCToJSWithString('這里是JS中alert彈出的message')";
//調(diào)用JS代碼 返回的是 JSValue? ------> 可轉(zhuǎn)換 成 對應(yīng)的OC對象
[_jsContext evaluateScript:textJS];
2茁瘦、JS調(diào)用OC
// *******************? JS調(diào)用原生OC (本質(zhì):重寫JS的方法) *******************
//第一種? 通過重寫 JS方法
/*
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//定義好JS要調(diào)用的方法, picCallback就是調(diào)用的picCallback方法名
//類似JS定義好一個方法,但是方法里面內(nèi)容是空的储笑, 我們在這里來 重寫 該方法的內(nèi)容甜熔, 當(dāng) JS 執(zhí)行命令是 來 調(diào)用 我們重寫的該方法的內(nèi)容
context[@"JSToOCWithNil"] = ^() {
NSLog(@"+++++++Begin Log+++++++");
NSArray *args = [JSContext currentArguments];
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"方式二" message:@"這是OC原生的彈出窗" delegate:self cancelButtonTitle:@"收到" otherButtonTitles:nil];
[alertView show];});
for (JSValue *jsVal in args) {
NSLog(@"------>%@", jsVal.toString);
}
NSLog(@"-------End Log-------");
};
//第二種 通過代理 調(diào)用OC重寫JS的方法
#import@protocol JSObjcDelegate//這是JS中的? &&&&&&標(biāo)簽對應(yīng)的名字 value對應(yīng)的名字&&&&&&/*
*/- (void)callCamera;
- (void)share:(NSString *)shareString;
@end
//獲取JS上下文
self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
self.jsContext[@"Toyun"] = self;
self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
context.exception = exceptionValue;
NSLog(@"異常信息:%@", exceptionValue);
};
#pragma mark - JSObjcDelegate
/*
JavaScript調(diào)用本地方法是在子線程中執(zhí)行的,這里要根據(jù)實(shí)際情況考慮線程之間的切換南蓬,而在回調(diào)JavaScript方法的時候最好是在剛開始調(diào)用此方法的線程中去執(zhí)行那段JavaScript方法的代碼纺非,我在實(shí)際運(yùn)用中開始沒注意,就被坑慘了啊
*/
- (void)callCamera {
NSLog(@"callCamera");
// 獲取到照片之后在回調(diào)js的方法picCallback把圖片傳出去
JSValue *JSToOCWithNil = self.jsContext[@"JSToOCWithNil"];
[JSToOCWithNil callWithArguments:@[@"photos"]];
}
- (void)share:(NSString *)shareString {
NSLog(@"share:%@", shareString);
// 分享成功回調(diào)js的方法shareCallback
JSValue *JSToOCWithString = self.jsContext[@"JSToOCWithString"];
[JSToOCWithString callWithArguments:nil];
}
二赘方、WKWebView :OC與JS交互
1烧颖、OC 調(diào)JS 類似 webVIew的方法
//替換第一個P元素內(nèi)容
NSString *tempString = [NSString stringWithFormat:@"document.getElementsByTagName('p')[0].innerHTML ='%@';",self.someString];
[self.myWebView evaluateJavaScript:tempString? completionHandler:^(id item, NSError * _Nullable error) {
}];
2、JS調(diào)OC
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
config.userContentController = [[WKUserContentController alloc] init];
// 注入JS對象Native窄陡,
// 聲明WKScriptMessageHandler 協(xié)議
// ?换础!L病M吭病!1姨尽润歉! 注冊監(jiān)聽的 JS方法名:Native和 Pay? ,只要名為Native或者 Pay的 回調(diào)代理 則會觸發(fā)颈抚,在代理里面進(jìn)行 方法名的判斷 進(jìn)行處理
[config.userContentController addScriptMessageHandler:self name:@"Native"];
//本人喜歡只定義一個MessageHandler協(xié)議 當(dāng)然可以定義其他MessageHandler協(xié)議
[config.userContentController addScriptMessageHandler:self name:@"Pay"];
self.myWebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
self.myWebView.UIDelegate = self;
[self.view addSubview:self.myWebView];
[self loadTouched:nil];
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message {
NSDictionary *bodyParam = (NSDictionary*)message.body;
NSString *func = [bodyParam objectForKey:@"function"];
NSLog(@"MessageHandler Name:%@", message.name);
NSLog(@"MessageHandler Body:%@", message.body);
NSLog(@"MessageHandler Function:%@",func);
//本人喜歡只定義一個MessageHandler協(xié)議 當(dāng)然可以定義其他MessageHandler協(xié)議
if ([message.name isEqualToString:@"Native"])
{
///參數(shù)
NSDictionary *parameters = [bodyParam objectForKey:@"parameters"];
//調(diào)用本地函數(shù)1
if([func isEqualToString:@"addSubView"])
{
Class tempClass =? NSClassFromString([parameters objectForKey:@"view"]);
CGRect frame = CGRectFromString([parameters objectForKey:@"frame"]);
if(tempClass && [tempClass isSubclassOfClass:[UIWebView class]])
{
UIWebView *tempObj = [[tempClass alloc] initWithFrame:frame];
tempObj.tag = [[parameters objectForKey:@"tag"] integerValue];
NSURL *url = [NSURL URLWithString:[parameters objectForKey:@"urlstring"]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[tempObj loadRequest:request];
[self.myWebView addSubview:tempObj];
}
}
//調(diào)用本地函數(shù)2
else if([func isEqualToString:@"alert"])
{
[self showMessage:@"來自網(wǎng)頁的提示" message:[parameters description]];
}
//調(diào)用本地函數(shù)3
else if([func isEqualToString:@"callFunc"])
{
}
//調(diào)用本地函數(shù)4
else if([func isEqualToString:@"testFunc"])
{
[self showMessage:@"來自網(wǎng)頁的字典" message:[parameters description]];
}
}
else if ([message.name isEqualToString:@"Pay"]) {
//如果是自己定義的協(xié)議, 再截取協(xié)議中的方法和參數(shù), 判斷無誤后在這里進(jìn)行邏輯處理
} else if ([message.name isEqualToString:@"dosomething"]) {
//........
}
}