JS WEB 交互问题

//
//  ViewController.m
//  OC与JS交互之UIWebView
//
//  Created by user on 16/8/15.
//  Copyright © 2016年 rrcc. All rights reserved.
//

#import "ViewController.h"
#define KSCreenSize [UIScreen mainScreen].bounds.size
@interface ViewController () <UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.webView.delegate = self;
    self.webView.backgroundColor = [UIColor redColor];
 
   //加载本地html 初始化webview
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSURL *baseURL = [[NSBundle mainBundle] bundleURL];
    [self.webView loadHTMLString:[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil] baseURL:baseURL];
}



- (IBAction)btnClick:(UIButton *)sender {
    //网页加载完成之后调用JS代码才会执行,因为这个时候html页面已经注入到webView中并且可以响应到对应方法
    if (sender.tag == 123) {
        [self.webView stringByEvaluatingJavaScriptFromString:@"alertMobile()"];
        //对应js内部    alert('我是上面的小黄 手机号是:13300001111')

    }
    
    if (sender.tag == 234) {
        [self.webView stringByEvaluatingJavaScriptFromString:@"alertName('小红')"];
         //alert('你好 ' + msg + ', 我也很高兴见到你')
    }
    
    if (sender.tag == 345) {
        [self.webView stringByEvaluatingJavaScriptFromString:@"alertSendMsg('18870707070','周末爬山真是件愉快的事情')"];
         //alert('这是我的手机号:' + num + ',' + msg + '!!')
    }
    /*
    总结: oc调用js代码
     效果:点击oc原声按钮 弹出webview aleartVew
    1 首选js代码需定义好提供给OC调用JS的方法列表,
     例如:
     //提供给OC调用JS的方法列表
                         function alertMobile() {
                         alert('我是上面的小黄 手机号是:13300001111')
                         }
                         
                         function alertName(msg) {
                         alert('你好 ' + msg + ', 我也很高兴见到你')
                         }
                         
                         function alertSendMsg(num,msg) {
                         alert('这是我的手机号:' + num + ',' + msg + '!!')
                         }

    2 webview 通过stringByEvaluatingJavaScriptFromString方法,调用js写好的代码,并传入参数。
     例如:
    // 原声按钮点击事件 调用的js代码
                         if (sender.tag == 234) {
                         [self.webView stringByEvaluatingJavaScriptFromString:@"alertName('小红')"];
                         //alert('你好 ' + msg + ', 我也很高兴见到你')
                         }

         
     
     */

}

#pragma mark - JS调用OC方法列表

- (void)showMobile {
    [self showMsg:@"我是下面的小红 手机号是:18870707070"];//oc代码
}

- (void)showName:(NSString *)name {
    NSString *info = [NSString stringWithFormat:@"你好 %@, 很高兴见到你",name];

    [self showMsg:info];//oc代码
}

- (void)showSendNumber:(NSString *)num msg:(NSString *)msg {
    NSString *info = [NSString stringWithFormat:@"这是我的手机号: %@, %@ !!",num,msg];
    
    [self showMsg:info];//oc代码
}




- (void)showMsg:(NSString *)msg {
    
    [[[UIAlertView alloc] initWithTitle:nil message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil] show];
}

#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSLog(@"-----%@",NSStringFromSelector(_cmd));//_cmd 当前方法
    NSLog(@"-----%@",request.URL);
    //OC调用JS是基于协议拦截实现的 下面是相关操作
    /*  rrcc://showMobile
        rrcc://showName_?xiaohuang
        rrcc://showSendNumber_msg_?13300001111&go%20climbing%20this%20weekend
     */
    NSString *absolutePath = request.URL.absoluteString;
   
    
    NSString *scheme = @"rrcc://";
    
    if ([absolutePath hasPrefix:scheme]) {
        NSString *subPath = [absolutePath substringFromIndex:scheme.length];//截取rrcc://得到后面的所有字符串
        
        if ([subPath containsString:@"?"]) {//1个或多个参数 js按钮3   rrcc://  showSendNumber_msg_?13300001111&go%20climbing%20this%20weekend
            
                if ([subPath containsString:@"&"]) {//多个参数
                    NSArray *components = [subPath componentsSeparatedByString:@"?"]; //showSendNumber_msg_ ;13300001111&go%20climbing%20this%20weekend
                    
                    NSString *methodName = [components firstObject];//showSendNumber_msg_
                    
                    methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];//showSendNumber:msg:
                    SEL sel = NSSelectorFromString(methodName);//showSendNumber:msg:

                    NSString *parameter = [components lastObject];//13300001111&go%20climbing%20this%20weekend
                    NSArray *params = [parameter componentsSeparatedByString:@"&"];//13300001111;go%20climbing%20this%20weekend

                    
                    if (params.count == 2) {
                        if ([self respondsToSelector:sel]) {
                            [self performSelector:sel withObject:[params firstObject] withObject:[params lastObject]];//showSendNumber(13300001111):msg:(go%20climbing%20this%20weekend)
                        }
                    }
                    

                } else {//1个参数 js按钮2   rrcc://  showName_?xiaohuang
                    NSArray *components = [subPath componentsSeparatedByString:@"?"];//showName_;xiaohuang
                    
                    NSString *methodName = [components firstObject];//showName_
                    methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];//showName:
                    SEL sel = NSSelectorFromString(methodName);//showName:

                    NSString *parameter = [components lastObject];//xiaohuang
                    
                    if ([self respondsToSelector:sel]) {
                        [self performSelector:sel withObject:parameter];//showName:
                    }

                }
                
        } else {//没有参数  js按钮1    rrcc://  showMobile
            NSString *methodName = [subPath stringByReplacingOccurrencesOfString:@"_" withString:@":"];
            SEL sel = NSSelectorFromString(methodName);//showMobile
            
            if ([self respondsToSelector:sel]) {//showMobile
                [self performSelector:sel];
            }
        }
    }
    
    return YES;
    /*
     效果:点击webview上的按钮,弹出oc原声aleartView
     总结:js调用oc代码
     
     操作:
     1 js代码定义好webview上的响应方法(本例监听按钮响应方法)
         //JS响应方法列表
         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"
         }

     2 oc通过webView代理方法- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType 
         截取url地址,解析地址根据按钮标签(),判断响应事件(本例判断每个按钮点击).
     
     NSString *absolutePath = request.URL.absoluteString;   //获取url地址 得到:rrcc://showMobile
     

         NSString *scheme = @"rrcc://";           //根据关键字解析
         
         if ([absolutePath hasPrefix:scheme]) {   //根据关键字解析
     
             if ([subPath containsString:@"?"]) {//1个或多个参数
             
                     if ([subPath containsString:@"&"]) {//多个参数
                         //点击  js按钮3
                     ps:获取js地址//showSendNumber_msg_13300001111&go%20climbing%20this%20weekend,解析地址中的包含的参数13300001111;go%20climbing%20this%20weekend,获取参数,为oc所用,包含交互信息两个.
     
                     } else {//1个参数 js按钮2
                         //点击  js按钮2  
                     ps:获取js地址rrcc://showName_?xiaohuang,解析地址中的包含的参数,获取参数xiaohuang,为oc所用,包含交互信息一个.
     
                     }
             
             } else {//没有参数
             
                    //点击  js按钮1
                    ps:获取js地址rrcc://showMobile,解析地址中的包含的参数无,无获取参数,纯粹监听事件,不包含交互信息一个.
     
            }
         }
     */
}


- (void)webViewDidStartLoad:(UIWebView *)webView {
    NSLog(@"%@",NSStringFromSelector(_cmd));
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSLog(@"%@",NSStringFromSelector(_cmd));
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:( NSError *)error {
    NSLog(@"%@",NSStringFromSelector(_cmd));
}
/*
 点击webViwe
 */

@end

 

<html>
    <!--描述网页信息-->
    <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>
            
            //提供给OC调用JS的方法列表
            function alertMobile() {
                alert('我是上面的小黄 手机号是:13300001111')
            }

            function alertName(msg) {
                alert('你好 ' + msg + ', 我也很高兴见到你')
            }

            function alertSendMsg(num,msg) {
                alert('这是我的手机号:' + num + ',' + msg + '!!')
            }
        
            //JS响应方法列表
            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>

    <!--网页具体内容-->
    <body>
        <br/><br/>

        <div>
            <label>小黄:13300001111</label>
        </div>
        <br/><br/>


        <div>
            <button class="btn" type="button" onclick="btnClick1()">小红的手机号</button>
        </div>
        <br/>

        <div>
            <button class="btn" type="button" onclick="btnClick2()">打电话给小红</button>
        </div>
        <br/>

        <div>
            <button class="btn" type="button" onclick="btnClick3()">发短信给小红</button>
        </div>


    </body>
</html>

 

posted @ 2016-10-20 15:36  看谷秀  阅读(272)  评论(0编辑  收藏  举报