iOS开发UIWebView和JS交互iOS之基础知识

WKWebView的简单使用

2016-11-04  本文已影响375人  芝麻绿豆

WKWebView-iOS 8出现的,比UIWebView性能高出很多!而且现在xcode也只支持到iOS8.0了,所以我们可以全面代替UIWebView了!

WKWebView是WebKit框架里的,所以需要导入:#import <WebKit/WebKit.h>

初始化一个WKWebView

WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.jianshu.com/users/ce9d64a894d8/latest_articles"]]];
[self.view addSubview:webView];

WKWebView代理协议:

遵守协议:

webView.UIDelegate= self;

实现协议里的方法:

 /**
*web界面中有弹出警告框时调用
 *在HTML中调用了JS的alert()方法时,就会回调此API
 *@param webView 实现该代理的webview
 *@param message 警告框中的内容
 *@param frame 主窗口
 *@param completionHandler 警告框消失调用
 */
-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message
                                                                             message:nil
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction *action) {
                                                          completionHandler();
                                                      }]];
    
    [self presentViewController:alertController animated:YES completion:^{}];
    NSLog(@"%@",completionHandler);
}
/*
 确认消息框Confirm
 */
-(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:^{}];
}
/*
 输入框TextInput
 */
-(void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *result))completionHandler{
    
    completionHandler(@"Client Not handler");
}

遵守协议:

webView.navigationDelegate = self;

实现协议方法:

/*
在发送请求之前,决定是否跳转
 WKNavigationActionPolicyCancel,
 WKNavigationActionPolicyAllow,
 */
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    /*
     WKNavigationTypeLinkActivated, href链接  0
     WKNavigationTypeFormSubmitted, 提交form  1
     WKNavigationTypeBackForward, back forward 2
     WKNavigationTypeReload,  刷新  3
     WKNavigationTypeFormResubmitted, 后退、前进,或重新加载  4
     WKNavigationTypeOther = -1,
     */
    NSLog(@"navigationType%ld",(long)navigationAction.navigationType);
    decisionHandler(WKNavigationActionPolicyAllow);
}
/**
 页面开始加载的时候调用
 @param webView    webView
 @param navigation 页面的导航对象
 */
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    [self.progressView setProgress:webView.estimatedProgress animated:YES];
}
/**
 在收到响应后,决定是否跳转
 */
-(void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    decisionHandler(WKNavigationResponsePolicyAllow);
}
/**
 页面开始接收内容时调用
 */
-(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{

}
/**
 页面加载完成时调用
 */
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    self.navigationItem.title = webView.title;
    [self.progressView setProgress:webView.estimatedProgress animated:YES];
    
}
/**
 接收到服务器跳转请求之后调用
 */
-(void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    
}
/**
 页面加载过程中失败时调用
 */
-(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    
}
/**
 页面加载内容失败时调用
 */
-(void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    
}

清除缓存

            NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
            NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
            [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes
                                                       modifiedSince:dateFrom               completionHandler:^{
                                                          
                                                       }];

遵守协议:

    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    WKUserContentController *userCC = [[WKUserContentController alloc] init];
    config.userContentController = userCC;
    WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];

注:是否其中JS:webView.configuration.preferences.javaScriptEnabled = YES;
在该页面注入JS函数:[config.userContentController addScriptMessageHandler:self name:@"backMallHome"];

实现协议:实现js调用OC方法

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

    if ([message.name isEqualToString:@"backMallHome"]) {
        
    }
}

self.webView.backForwardList.currentItem.URL.absoluteString / backItem.URL.absoluteString / forwardItem.URL.absoluteString 等一些方法可以获取到不同情况下的URL

JS与OC互调

window.webkit.messageHandlers.backMallHome.postMessage(['返回商城首页']); 
    [self.webView evaluateJavaScript:[NSString stringWithFormat:@"login(\"%@\")",[AppTool showLoginInfo].username] completionHandler:^(id _Nullable response, NSError * _Nullable error) {

    }];

JS兼容Android、iOS

//判断访问终端
var browser={
versions:function(){

    var u = navigator.userAgent, 
    app = navigator.appVersion;
    return {
        trident: u.indexOf('Trident') > -1, //IE内核
        presto: u.indexOf('Presto') > -1, //opera内核
        webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
        gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
        mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
        ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
        android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
        iPhone: u.indexOf('iPhone') > -1 , //是否为iPhone或者QQHD浏览器
        iPad: u.indexOf('iPad') > -1, //是否iPad
        webApp: u.indexOf('Safari') == -1, //是否web应该程序,没有头部与底部
        weixin: u.indexOf('MicroMessenger') > -1, //是否微信 (2015-01-22新增)
        qq: u.match(/\sQQ/i) == " qq" //是否QQ
    };
    }(),
    language:(navigator.browserLanguage || navigator.language).toLowerCase()
    }

//判断是否移动端
browser.versions.android
browser.versions.ios

模拟器调试H5页面:

打开Safari 断点调试

感谢您的阅读,希望对您有所帮助!欢迎任何形式的转载,但请务必注明出处,尊重他人劳动!

上一篇下一篇

猜你喜欢

热点阅读