您的位置:首页 > 移动开发

WKWebView的使用及js交互Demo

2016-09-06 14:48 417 查看
iOS代码:

#import "TestForWkWebviewViewController.h"

#define SCREEN_RECT [UIScreen mainScreen].bounds

//刨去状态栏的尺寸

#define SCREEN_REMOVE_APPLICATION  [UIScreen mainScreen].applicationFrame

@interface TestForWkWebviewViewController ()<</span>WKNavigationDelegate, WKUIDelegate,WKScriptMessageHandler>{

    WKWebView *Web;

}

@end

// 页面开始加载时调用

//- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation;

// 当内容开始返回时调用

//- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation;

// 页面加载完成之后调用

//- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation;

// 页面加载失败时调用

//- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation;

// 接收到服务器跳转请求之后调用

//- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation;

// 在收到响应后,决定是否跳转

//- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler;

// 在发送请求之前,决定是否跳转

//- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;

@implementation TestForWkWebviewViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    WKWebViewConfiguration *config
= [[WKWebViewConfiguration alloc] init];

    //注册js方法

    [config.userContentController addScriptMessageHandler:self name:@"webViewApp"];

    Web = [[WKWebView alloc]initWithFrame:SCREEN_RECT configuration:config];

//    NSURL *baidu = [NSURL URLWithString:@"http://www.youshaa.cn/app/boutique"];

//    NSURLRequest *request = [NSURLRequest requestWithURL:baidu];

//    [Web loadRequest:request];

    //加载本地页面

    [Web loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL fileURLWithPath:[[NSBundlemainBundle] pathForResource:@"test" ofType:@"html"]]]];

    Web.navigationDelegate = self;

    Web.UIDelegate = self;

    [self.view addSubview:Web];

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

//实现js调用iOS的handle委托

- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message{

    //接受传过来的消息从而决定app调用的方法

    NSDictionary *dict = message.body;

    NSString *method = [dict objectForKey:@"method"];

    if ([method isEqualToString:@"hello"])
{

        [self hello:[dict objectForKey:@"param1"]];

    }else if ([method isEqualToString:@"Call
JS"]){

        [self callJS];

    }else if ([method isEqualToString:@"Call
JS Msg"]){

        [self callJSMsg:[dict objectForKey:@"param1"]];

    }

}

//直接调用js

//webView.evaluateJavaScript("hi()", completionHandler: nil)

//调用js带参数

//webView.evaluateJavaScript("hello('liuyanwei')", completionHandler: nil)

//调用js获取返回值

//webView.evaluateJavaScript("getName()") { (any,error) -> Void in

//    NSLog("%@", any as! String)

//}

- (void)hello:(NSString *)param{

    [self showAlert:param Title:@"js
Call iOS"];

}

- (void)callJS{

    [Web evaluateJavaScript:@"iOSCallJSNO()" completionHandler:nil];

}

- (void)callJSMsg:(NSString *)msg{

    [Web evaluateJavaScript:[NSString stringWithFormat:@"iOSCallJS('%@')",msg]completionHandler:nil];

}

//WKNavigationDelegate

// 页面开始加载时调用

- (void)webView:(WKWebView *)webView
didStartProvisionalNavigation:(WKNavigation *)navigation {// 类似UIWebView的 -webViewDidStartLoad:

    NSLog(@"didStartProvisionalNavigation");

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

}

// 当内容开始返回时调用

- (void)webView:(WKWebView *)webView
didCommitNavigation:(WKNavigation *)navigation {

    NSLog(@"didCommitNavigation");

}

// 页面加载完成之后调用

- (void)webView:(WKWebView *)webView
didFinishNavigation:(WKNavigation *)navigation { // 类似UIWebView 的 -webViewDidFinishLoad:

    NSLog(@"didFinishNavigation");

    //[self resetControl];

    if (webView.title.length > 0)
{

        self.title =
webView.title;

    }

    

}

// 页面加载失败时调用

- (void)webView:(WKWebView *)webView
didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error
{

    // 类似 UIWebView 的-
webView:didFailLoadWithError:

    NSLog(@"didFailProvisionalNavigation");

}

// 在收到响应后,决定是否跳转

- (void)webView:(WKWebView *)webView
decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
{

    

    decisionHandler(WKNavigationResponsePolicyAllow);

}

// 在发送请求之前,决定是否跳转

- (void)webView:(WKWebView *)webView
decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{

    // 类似 UIWebView 的 -webView:
shouldStartLoadWithRequest: navigationType:

    NSLog(@"4.%@",navigationAction.request);

//    NSString *url = [navigationAction.request.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

//    NSString *url = navigationAction.request.URL.absoluteString;

    decisionHandler(WKNavigationActionPolicyAllow);

    

}

// 接收到服务器跳转请求之后调用

- (void)webView:(WKWebView *)webView
didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{

    NSLog(@"didReceiveServerRedirectForProvisionalNavigation");

}

//- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition,
NSURLCredential *))completionHandler {

//    completionHandler(NSURLSessionAuthChallengePerformDefaultHandling,internal);

//}

//WKUIDelegate

- (WKWebView *)webView:(WKWebView *)webView
createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction*)navigationAction
windowFeatures:(WKWindowFeatures *)windowFeatures {

    // 接口的作用是打开新窗口委托

    //[self createNewWebViewWithURL:webView.URL.absoluteString config:Web];

    

    return Web;

}

- (void)webView:(WKWebView *)webView
runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame
completionHandler:(void (^)(void))completionHandler

{    // js 里面的alert实现,如果不实现,网页的alert函数无效

    UIAlertController *alertController
= [UIAlertController alertControllerWithTitle:message

                                                                             message:nil

                                                                      preferredStyle:UIAlertControllerStyleAlert];

    [alertController addAction:[UIAlertAction actionWithTitle:@"确定"

                                                        style:UIAlertActionStyleCancel

                                                      handler:^(UIAlertAction *action)
{

                                                          completionHandler();

                                                      }]];

    

    [self presentViewController:alertController animated:YES completion:^{

        

    }];

    

}

//  js 里面的alert实现,如果不实现,网页的alert函数无效

- (void)webView:(WKWebView *)webView
runJavaScriptConfirmPanelWithMessage:(NSString*)message initiatedByFrame:(WKFrameInfo *)frame
completionHandler:(void (^)(BOOL))completionHandler
{

    UIAlertController *alertController
= [UIAlertController alertControllerWithTitle:message

                                                                             message:nil

                                                                      preferredStyle:UIAlertControllerStyleAlert];

    [alertController addAction:[UIAlertAction actionWithTitle:@"确定"

                                                        style:UIAlertActionStyleDefault

                                                      handler:^(UIAlertAction *action)
{

                                                          completionHandler(YES);

                                                      }]];

    [alertController addAction:[UIAlertAction actionWithTitle:@"取消"

                                                        style:UIAlertActionStyleCancel

                                                      handler:^(UIAlertAction *action){

                                                          completionHandler(NO);

                                                      }]];

    

    [self presentViewController:alertController animated:YES completion:^{}];

    

}

- (void)webView:(WKWebView *)webView
runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText
initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void(^)(NSString *))completionHandler
{

    

    completionHandler(@"Client Not handler");

    

}

 

- (void)showAlert:(NSString *)content
Title:(NSString *)title{

    UIAlertController *alertController
= [UIAlertController alertControllerWithTitle:title

                                                                             message:content

                                                                      preferredStyle:UIAlertControllerStyleAlert];

    

    [alertController addAction:[UIAlertAction actionWithTitle:@"确定"

                                                        style:UIAlertActionStyleCancel

                                                      handler:^(UIAlertAction *action)
{

                                                          [self.navigationController popToRootViewControllerAnimated:YES];

                                                      }]];

    [self presentViewController:alertController animated:YES completion:^{

        

    }];

}

@end

Html代码:

 

<!DOCTYPE html>

<html>

<head>

        <meta
http-equiv="Content-Type"
content="text/html; charset=utf-8" />

        <title>测试iOS与JS之间的互调</title>

        <style
type="text/css">

            * {

                font-size:
40px;

            }

        </style>

</head>

<body>

        <div
style="rargin-top: 100px;">

            <h1>Test how to use objective-c call js</h1>

            <input
type="button"
value="Call iOS"
onclick="calliOS('call iOS')">

            <input
type="button"
value="Call JS Alert"
onclick="jsFunc()">

        </div>

        <div>

            <input
type="button"
value="iOS Call With No JSON"
onclick="callJS()">

            <input
type="button"
value="iOS Call With JSON"
onclick="callJSMsg('iOS Call JS')">

        </div>

        <div>

            <span
id="jsParatFuncSpan"
style="color:red; font-size:50px;"></span>

        </div>

        <script
type="text/javascript">

            function calliOS(Msg) {

                var message = {

                    'method' :
'hello',

                    'param1' : Msg,

                };

                window.webkit.messageHandlers.webViewApp.postMessage(message);

            }

            function callJS() {

                var message = {

                    'method' :
'Call JS',

                };

                window.webkit.messageHandlers.webViewApp.postMessage(message);

            }

            function callJSMsg(Msg) {

                var message = {

                    'method' :
'Call JS Msg',

                    'param1' : Msg,

                };

                window.webkit.messageHandlers.webViewApp.postMessage(message);

            }

            function jsFunc() {

                alert('Hello World');

            }

            function iOSCallJSON() {

                alert('call no msg');

            }

            function iOSCallJS(Msg) {

                alert(Msg);

            }

        </script>

</body>

</html>

原文地址:http://blog.sina.com.cn/s/blog_c4fb92f60102w65o.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iOS