js與OC互相調(diào)用 —— UIWebview攔截Url

簡(jiǎn)單整理了下在ios編譯環(huán)境下,oc與js相互調(diào)用通過UIWebview攔截url,達(dá)到實(shí)現(xiàn)效果。
1.創(chuàng)建本地html文件


html文件.png

2.創(chuàng)建UIWebview

 self.webView = [[UIWebView alloc] initWithFrame:self.view.frame];
    self.webView.delegate = self;
    NSURL *htmlURL = [[NSBundle mainBundle] URLForResource:@"index.html" withExtension:nil];
//    NSURL *htmlURL = [NSURL URLWithString:@"http://www.baidu.com"];
    NSURLRequest *request = [NSURLRequest requestWithURL:htmlURL];
    
    // 如果不想要webView 的回彈效果
    self.webView.scrollView.bounces = NO;
    // UIWebView 滾動(dòng)的比較慢,這里設(shè)置為正常速度
    self.webView.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
    [self.webView loadRequest:request];
    [self.view addSubview:self.webView];

3.通過UIWebViewDelegate代理方法攔截Url

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL *URL = request.URL; // haleyaction://scanClick

    NSString *scheme = [URL scheme]; // haleyaction
    if ([scheme isEqualToString:@"haleyaction"]) {
        [self handleCustomAction:URL];
        return NO;
    }
    
    return YES;
}

通過判斷scheme判斷實(shí)現(xiàn)不同的方法

- (void)handleCustomAction:(NSURL *)URL
{
    NSString *host = [URL host];
    if ([host isEqualToString:@"scanClick"]) {
        NSLog(@"掃一掃");
    } else if ([host isEqualToString:@"shareClick"]) {
        [self share:URL];
    } else if ([host isEqualToString:@"getLocation"]) {
        [self getLocation];
    } else if ([host isEqualToString:@"setColor"]) {
        [self changeBGColor:URL];
    } else if ([host isEqualToString:@"payAction"]) {
        [self payAction:URL];
    } else if ([host isEqualToString:@"shake"]) {
        [self shakeAction];
    } else if ([host isEqualToString:@"goBack"]) {
        [self goBack];
    }
}

回調(diào)結(jié)果到j(luò)s中

- (void)getLocation
{
    // 獲取位置信息
    // 將結(jié)果返回給js
    NSString *jsStr = [NSString stringWithFormat:@"setLocation('%@')",@"廣東省深圳市南山區(qū)學(xué)府路XXXX號(hào)"];
    [self.webView stringByEvaluatingJavaScriptFromString:jsStr];
}

在js中把參數(shù)傳給OC

  function shareClick() {
                loadURL("haleyAction://shareClick?title=測(cè)試分享的標(biāo)題&content=測(cè)試分享的內(nèi)容&url=http://www.baidu.com");
            }

獲取傳遞過來的參數(shù),通過相關(guān)重要參數(shù)分割,組成新的字典

- (void)share:(NSURL *)URL
{
    // URL.query ===》 title=%E6%B5%8B%E8%AF%95%E5%88%86%E4%BA%AB%E7%9A%84%E6%A0%87%E9%A2%98&content=%E6%B5%8B%E8%AF%95%E5%88%86%E4%BA%AB%E7%9A%84%E5%86%85%E5%AE%B9&url=http://www.baidu.com
    NSArray *params =[URL.query componentsSeparatedByString:@"&"];
    /*
     <__NSArrayM 0x60400044af80>(
     title=%E6%B5%8B%E8%AF%95%E5%88%86%E4%BA%AB%E7%9A%84%E6%A0%87%E9%A2%98,
     content=%E6%B5%8B%E8%AF%95%E5%88%86%E4%BA%AB%E7%9A%84%E5%86%85%E5%AE%B9,
     url=http://www.baidu.com
     )
     */
    NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
    for (NSString *paramStr in params) {
        NSArray *dicArray = [paramStr componentsSeparatedByString:@"="];
        if (dicArray.count > 1) {
            NSString *decodeValue = [dicArray[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [tempDic setObject:decodeValue forKey:dicArray[0]];
            /*
             
             (lldb) po tempDic
             {
             content = "\U6d4b\U8bd5\U5206\U4eab\U7684\U5185\U5bb9";
             title = "\U6d4b\U8bd5\U5206\U4eab\U7684\U6807\U9898";
             url = "http://www.baidu.com";
             }
             
             */
        }
    }
    
    NSString *title = [tempDic objectForKey:@"title"];
    NSString *content = [tempDic objectForKey:@"content"];
    NSString *url = [tempDic objectForKey:@"url"];
    // 在這里執(zhí)行分享的操作
    
    // 將分享結(jié)果返回給js 劃重點(diǎn)
    NSString *jsStr = [NSString stringWithFormat:@"shareResult('%@','%@','%@')",title,content,url];
    [self.webView stringByEvaluatingJavaScriptFromString:jsStr];
}

OC調(diào)用JS方法


oc調(diào)用Js方法.png

在OC中的方法調(diào)用

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
   [webView stringByEvaluatingJavaScriptFromString:@"var arr = [3, 4, 'abc'];"];
}

實(shí)現(xiàn)效果


js與oc交互.gif

注意事項(xiàng)

如果回調(diào)執(zhí)行的JS 方法帶參數(shù),而參數(shù)不是字符串時(shí),不要加單引號(hào),否則可能導(dǎo)致調(diào)用JS 方法失敗。比如我這樣的:

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userProfile options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *jsStr = [NSString stringWithFormat:@"loginResult('%@',%@)",type, jsonStr];
[_webView stringByEvaluatingJavaScriptFromString:jsStr];
如果第二個(gè)參數(shù)用單引號(hào)包起來,就會(huì)導(dǎo)致JS端的loginResult不會(huì)調(diào)用。

注意要點(diǎn)在oc中調(diào)用js中方法,方法名稱和參數(shù)均要一一對(duì)應(yīng)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容