上篇文章講過穴肘,oc和js交互,oc調(diào)用js關(guān)鍵的方法是
- (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;
這篇文章講的是js如何調(diào)用oc违寿,js調(diào)用oc的關(guān)鍵方法是
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
一、寫一個簡單的html網(wǎng)頁熟空,3個p標簽藤巢。
js代碼
二、實現(xiàn)UIWebViewDelegate的代理方法痛阻。
request.URL.scheme 協(xié)議菌瘪。
request.URL.absoluteString 絕對路徑。
//每當webView即將發(fā)送一個請求之前阱当,都會調(diào)用這個方法
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSLog(@"scheme = %@",request.URL.scheme);
NSLog(@"absoluteString = %@",request.URL.absoluteString);
NSArray *array = [request.URL.absoluteString componentsSeparatedByString:@"?"];
NSLog(@"array = %@",array);
//判斷連接是否存在
if ([request.URL.scheme isEqualToString:@"clickp"]) {
//說明沒有參數(shù)
if (array.count==1) {
SEL sel = NSSelectorFromString(request.URL.scheme);
[self performSelector:sel withObject:nil withObject:nil];
}else if(array.count == 2){//說明有1個參數(shù)
SEL sel = NSSelectorFromString([NSString stringWithFormat:@"%@:",request.URL.scheme]);
[self performSelector:sel withObject:[array lastObject] withObject:nil];
}else if (array.count == 3){//說明有2個參數(shù)
SEL sel = NSSelectorFromString([NSString stringWithFormat:@"%@:message:",request.URL.scheme]);
[self performSelector:sel withObject:array[1] withObject:[array lastObject]];
}
}
三俏扩、點擊p標簽,執(zhí)行UIWebViewDelegate的代理方法弊添,調(diào)用oc代碼
//點擊第一個p標簽
- (void)clickp{
self.showTop.text = @"點擊了第一個p標簽";
}
//點擊第二個p標簽
- (void)clickp:(NSString *)message{
NSString *new = [message stringByRemovingPercentEncoding];
self.showCenter.text = new;
}
//點擊第三個p標簽
- (void)clickp:(NSString *)firstMessage message:(NSString *)lastMessage{
NSString *firstParam = [firstMessage stringByRemovingPercentEncoding];
NSString *lastParam = [lastMessage stringByRemovingPercentEncoding];
self.showBottom.text = [NSString stringWithFormat:@"%@ %@",firstParam,lastParam];
}
實例圖片:
github地址:https://github.com/shimminZ/JsCallOC.git
歡迎star.