美文网首页
vue与ios交互

vue与ios交互

作者: 稀释1 | 来源:发表于2020-05-12 19:57 被阅读0次

    vue
    这段代码很重要 ios调用的方法要这样不然调不通

       mounted:function () {
                window.tapClick = this.tapClick;
            },
    
    <template>
        <div id="app">
    
            <label v-on:click="tapClick">点击</label>
            <button v-on:click="jsSendAlertToOC">js调用原生警告面板</button>
            <br>
            <br>
            <button v-on:click="jsSendConfirmToOC">js调用原生确认</button>
            <br>
            <br>
            <button v-on:click="jsSendInputToOC">js调用输入框</button>
            <br>
            <br>
            <button v-if="xianshi" v-on:click="jsSendMessageToOC">js发送数据给原生</button>
            <br>
            <br>
            <div id="showMessage"></div>
        </div>
    </template>
    
    <script>
    
        export default {
            name: 'App',
            components: {},
            data(){
                return{
                    xianshi:false
                }
    
            },
    
            mounted:function () {
                window.tapClick = this.tapClick;
            },
            methods: {
                tapClick() {
                   
                    this.xianshi = !this.xianshi
    
                    window.webkit.messageHandlers.messageSend.postMessage('啦啦啦');
    
    
                },
                jsSendAlertToOC:function() {
                    alert('js调用原生警告面板');
                },
                jsSendConfirmToOC() {
                    if (confirm('js 调用原生确认面板')) {
                        document.getElementById('showMessage').innerHTML
                            = 'true';
                    } else {
                        document.getElementById('showMessage').innerHTML
                            = 'false';
                    }
                },
                jsSendInputToOC() {
                    var response = prompt('请输入您的测试数据');
                    document.getElementById('showMessage').innerHTML = response;
                },
                jsSendMessageToOC() {
                    // <!--通过 [config.userContentController addScriptMessageHandler:self name:@"messageSend"]; 注入"messageSend"来发出消息-->
                    window.webkit.messageHandlers.messageSend.postMessage({a: 10, b: 'c'})
    
                }
    
            }
        }
    </script>
    

    oc

    #import "webViewController.h"
     #import <WebKit/WebKit.h>
    @interface webViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>
    @property(nonatomic,strong)WKWebView *webView;
    @end
    
    @implementation webViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.view.backgroundColor = [UIColor whiteColor];
     
            WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        //    注入方法 messageSend 在js中通过注入的方法向原生OC传值。
            config.userContentController = [[WKUserContentController alloc] init];
            [config.userContentController addScriptMessageHandler:self name:@"messageSend"];
        //    偏好设置
            config.preferences = [[WKPreferences alloc] init];
            config.preferences.minimumFontSize = 0;
            config.preferences.javaScriptEnabled = YES;
            config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
            _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) configuration:config];
            //如果使用本地html文件
        //    NSURL *path = [[NSBundle mainBundle] URLForResource:@"NativeJS" withExtension:@"html"];
            [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://172.26.105.119:8080/"]]];
            _webView.UIDelegate = self;
            _webView.navigationDelegate = self;
            [self.view addSubview:_webView];
            
            //    监听_webview 的状态
    //        [_webView addObserver:self forKeyPath:@"loading" options:NSKeyValueObservingOptionNew context:nil];
    //        [_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
            [_webView addObserver:self forKeyPath:@"estimaedProgress" options:NSKeyValueObservingOptionNew context:nil];
        
        
        
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(10, [UIScreen mainScreen].bounds.size.height-120, 80, 80)];
        [btn setBackgroundColor:[UIColor redColor]];
        [self.view addSubview:btn];
        [btn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    
    }
    #pragma mark - WKUIDelegate
    //通过js alert 显示一个警告面板,调用原生会走此方法。
    - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
    {
        NSLog(@"显示一个JavaScript警告面板, message = %@",message);
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            completionHandler();
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    //通过 js confirm 显示一个确认面板,调用原生会走此方法。
    - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler
    {
        NSLog(@"运行JavaScript确认面板, message = %@", message);
        UIAlertController *action = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
        [action addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            completionHandler(NO);
        }] ];
        [action addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            completionHandler(YES);
        }]];
        [self presentViewController:action animated:YES completion:nil];
    }
    #pragma mark - WKScriptMessageHandler
    //当js 通过 注入的方法 @“messageSend” 时会调用代理回调。 原生收到的所有信息都通过此方法接收。
    -(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
    {
        NSLog(@"原生收到了js发送过来的消息 message.body = %@",message.body);
        if ([message.name isEqualToString:@"messageSend"]) {
    //        pushViewController *congtoller = [[pushViewController alloc] init];
    //        [self.navigationController pushViewController:congtoller animated:YES];
        }
    }
    //显示输入框
    - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler
    {
        NSLog(@"显示一个JavaScript文本输入面板, message = %@",prompt);
        UIAlertController *controller = [UIAlertController alertControllerWithTitle:defaultText message:prompt preferredStyle:UIAlertControllerStyleAlert];
        [controller addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.textColor = [UIColor redColor];
        }];
        [controller addAction:[UIAlertAction actionWithTitle:@"输入信息" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            completionHandler([[controller.textFields lastObject] text]);
        }]];
        [self presentViewController:controller animated:YES completion:nil];
    }
    -(void)backClick{
        NSLog(@"反悔了");
    //     [_iWKWebView goBack];
           NSString *js = @"tapClick()";
        //    NSString *js = @"jsSendAlertToOC()";
        //    NSString *js = @"jsSendInputToOC()";
        //    NSString *js = @"jsSendMessageToOC()";
           
    // 发送消息给js
           [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable resp, NSError * _Nullable error) {
               NSLog(@"error = %@ , response = %@",error, resp);
           }];
    }
    

    相关文章

      网友评论

          本文标题:vue与ios交互

          本文链接:https://www.haomeiwen.com/subject/wkpinhtx.html