>

建议使用WKWebView替代UIWebViewsbf282.com,跳转之后拨

- 编辑:澳门博发娱乐官网 -

建议使用WKWebView替代UIWebViewsbf282.com,跳转之后拨

In apps that run in iOS 8 and later, use the WKWebView class instead of using UIWebView. Additionally, consider setting the WKPreferences property javaScriptEnabled to NO if you render files that are not supposed to run JavaScript.那是Apple Library里UIWebView部分的note,也等于说从iOS8起来,建议利用WKWebView代替UIWebView,就疑似UIAlertViewController替代UIAlertView同样,这一次正好要做三个H5的页面和应用程式实行交互,比较于UIWebView,WK的加载速度快了一倍,但攻陷的内部存储器却少了,WK也新增添了一些措施,使用起来更方便人民群众,上边就说说WKWebView的主干选择,来落实简单的web页面交互上代码:1、首先得引进库文件,WKWebView是WebKit的,#import <WebKit/WebKit.h>2、注解属性:@property (strong,nonatomic) WKWebView *webView;3、初始化: _webView = [[WKWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];4、说一说怎么着加多透明的网页,在此以前或然设置背景观为clearColor就能够,但是WK不行:_webView.backgroundColor = [UIColor clearColor];_webView.opaque = NO;5、设置代理,WK有多个代理WKUIDelegate,WKNavigationDelegate,交互涉及到的首要的第4个里面包车型客车代办方法,所以:_webView.navigationDelegate = self;6、早先加载web内容:NSU福特ExplorerLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:alertObj[@"h5"]]];[_webView loadRequest:request];7、加载完结,展现网页

iOS8从此,苹果推出了新框架Webkit,提供了替换UIWebView的机件WKWebView。种种UIWebView的主题材料没有了,速度更加快了,占用内部存款和储蓄器少了,一句话,WKWebView是App内部加载网页的极品选项!
一、WKWebView新特性
在品质、牢固性、功用方面有异常的大进级(最直观的反映便是加载网页是占用的内部存款和储蓄器,模拟器加载百度与开源中中原人民共和国网址时,WKWebView占用23M,而UIWebView占用85M);
允许JavaScript的Nitro库加载并行使(UIWebView中限制);
支撑了越来越多的HTML5特性;
高达60fps的轮转刷新率以及内置手势;
将UIWebViewDelegate与UIWebView重构成了14类与3个契约(翻开苹果官方文书档案);
二、初始化

WKWebView基类封装

一.引言

日前应公司要求,把品种里用到的UIWebView全都用WKWebView替换掉。于是就去切磋了WKWebview,加上在使用中相遇的某个主题材料加以总括,如有不足之处,还望建议,自个儿将会加以修改。

UIWebView自iOS2就有,WKWebView从iOS8才有,确实无疑WKWebView将渐次替代笨重的UIWebView。通过轻便的测量检验就可以发掘UIWebView攻下过多内存,且内部存款和储蓄器峰值更是夸大其词。WKWebView网页加载速度也许有升级,不过并不像内部存款和储蓄器那样进步那么多。下边罗列部分其余的优势:

  • 越来越多的支撑HTML5的特色
  • 法定证明的高达60fps的滚动刷新率以及内置手势
  • Safari相同的JavaScript引擎
  • 将UIWebViewDelegate与UIWebView拆分成了14类与3个左券(合立陶宛(Lithuania)语档表达)
  • 其它用的可比多的,扩充加载进程属性:estimatedProgress

缺欠:   WKWebView 不援救缓存 和   NSU奥迪Q3LProtocol 拦截了

在ios中,用H5编写了足以通话的页面。点击“拨打”开关后能够开展跳转到打电话的页面(跳转这一块应该是和浏览器有关),跳转之后拨打完电话能够回来从前打电话的页面。

  • webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{[[UIApplication sharedApplication].keyWindow addSubview:_webView];}接下里正是互相部分了这里最重要选取的是顾客点击web页面包车型客车开关,App拦截下来,在App端实行拍卖当客户点击页面包车型地铁按键,会走
  • webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(WKNavigationActionPolicy))decisionHandler;那些代理函数,大家就在那几个中举办拦截。
  • webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(WKNavigationActionPolicy))decisionHandler {NSURL *responseUrl = navigationAction.request.URL;NSString *urlStr = [responseUrl absoluteString];if ([[responseUrl scheme] isEqualToString:baseUrlScheme]) {if ([urlStr containsString:baseShareUrlPath]) {//点击马上分享[VPKCShare showShareWithPlatformImages:@[@"fx_pengyouquan"]];decisionHandler(WKNavigationActionPolicyCancel);} else if([responseUrl.path containsString:baseCloseUrlPath]){//点击关闭[_webView removeFromSuperview];decisionHandler(WKNavigationActionPolicyCancel);} else if([responseUrl.path containsString:baseGetUrlPath]){//点击马上领取decisionHandler(WKNavigationActionPolicyAllow);} else {decisionHandler(WKNavigationActionPolicyAllow);}} else {decisionHandler(WKNavigationActionPolicyAllow);}}就是将要跳转的url拿来扩充相比,假若是大家要阻止的url,就实施decisionHandler(WKNavigationActionPolicyCancel);要是否,就举行decisionHandler(WKNavigationActionPolicyAllow);就如UIWebView里的代理海曙重临YES和NO同样,那一个是一定要写的,不然程序就能够崩溃。关于相互,还只怕有四个类似的代办函数1、收到服务器的response后调用
  • webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(WKNavigationResponsePolicy))decisionHandler;2、服务器redirect时调用
  • webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation;
  1. 第一需求引进WebKit库

项目一直利用UIWebView,相关基类方法封装使用比较完善,业务量重,想完全替换为WKWebView有一些难度,必要时刻周密。所以本身在投机的demo中早先封装了WKWebView,参谋原有的类其他UIWebView。

二、UIWebView使用验证

先是步:其实就是出殡和埋葬了三个get央浼,url正是:tel:13587454758;与h5交互:获取到电话号码(U奇骏L);

第二步:[self openUrl:url];

第三步:

-(void)openUrl:(NSString *)urlStr{

NSURL *url = [NSURL URLWithString:urlStr];

UIApplication *application = [UIApplication sharedApplication];

if (![application canOpenURL:url]) {

NSLog(@"不可能开荒"%@", 请确认保证此选拔准确安装", url);

}else

[[UIApplication sharedApplication]openURL:url];

}

import <WebKit/WebKit.h>

  1. 开首化方法分为以下三种
    // 默许开始化
  • (instancetype)initWithFrame:(CGRect)frame;
    // 根据对webview的有关安插,实行起先化
  1. 加载网页与HTML代码的章程与UIWebView一样,代码如下:
    WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]];
    [self.view addSubview:webView];
    三、 WKWebView的代办方法

  2. WKNavigationDelegate

该代理提供的法门,能够用来追踪加载进程(页面早先加载、加载成功、加载失利)、决定是不是实践跳转。

// 页面最早加载时调用

  • (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;
    最重大的代办方法是收获ULANDL页面跳转

BaseViewController

1 举个例子:轻巧的使用

UIWebView运用特别轻巧,能够分为三步,也是最简便易行的用法,展现网页

// 1.创办webview,并安装大小,"20"为状态栏中度

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,20,self.view.frame.size.width,self.view.frame.size.height -20)];

// 2.创设供给

NSMutableURLRequest *request =[NSMutableURLRequestrequestWithURL:[NSURLURLWithString:@"];

// 3.加载网页

[webView loadRequest:request];

// 最后将webView加多到分界面

[self.view addSubview:webView];

获得网页url格局:

1.UIWebView

方法1:NSString *location =[webViewstringByEvaluatingJavaScriptFromString:@"document.location"];

方法2:NSLog(@"webView location = '%@'", webView.request.URL.absoluteString);

以上两种自然要放在页面成功加载之后才可以的!

- (void)webViewDidFinishLoad:(UIWebView *)webView {

NSString*currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];

}

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request

navigationType:(UIWebViewNavigationType)navigationType {

// 推断是还是不是是单击

if (navigationType == UIWebViewNavigationTypeLinkClicked) {

NSString *currentURL= myWebView.request.URL.absoluteString;

NSLog(@"你单击的网站是:%@", currentU安德拉L);

}

return YES;

}

2.WKWebview

#pragma mark 在发送乞求此前,决定是或不是跳转

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

//    NSLog(@"%s",__FUNCTION__);

/**

*typedef NS_ENUM(NSInteger, WKNavigationActionPolicy) {

WKNavigationActionPolicyCancel, // 取消

WKNavigationActionPolicyAllow,  // 继续

}

*/

NSString *reqUrl = [navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];

decisionHandler(WKNavigationActionPolicyAllow);

}

pragma mark - WKNavigationDelegate

  • (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSString *requestUrl = navigationAction.request.URL.absoluteString;
    if([requestUrl isEqualToString:_requestUrl]){
    decisionHandler(WKNavigationActionPolicyAllow);//允许加载U福睿斯L 也正是webView的return Yes;

    }else{
    decisionHandler(WKNavigationActionPolicyCancel);// 相当于webView的return NO;
    }
    }

由于后续导航栏重回事件须求管理,自定义BaseViewController,自定义重临方法。代码如下:

- (void)viewDidLoad {

    [super viewDidLoad];

    [self setBaseView];

}

- (void)setBaseView{

    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"title_new_back"] style:UIBarButtonItemStylePlain target:self action:@selector(backButtonAction:)];

    NSInteger index = [self.navigationController.viewControllers indexOfObject:self];

    if (index != 0) {

        self.navigationItem.leftBarButtonItem = item;

    }

}

- (void)backButtonAction:(UIBarButtonItem *)item{

    Class backController = NSClassFromString(self.backController);

    NSArray *reverseArray = [[self.navigationController.viewControllers reverseObjectEnumerator] allObjects];

    if (!self.backController) {

        [self.navigationController popViewControllerAnimated:YES];

    }else {

        for (UIViewController *controller in reverseArray) {

            if ([controller isKindOfClass:backController]) {

                [self.navigationController popToViewController:controller animated:YES];

                break;

            }

        }

    }

}

2 一些实用函数

  • 加载函数。

  • (void)loadRequest:(NSURLRequest *)request;

  • (void)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;

  • (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL;

UIWebView不止能够加载HTML页面,还支持pdf、word、txt、各类图片等等的来得。下边以加载mac桌面上的png图片:/Users/coohua/Desktop/bigIcon.png为例

// 1.获取url

NSURL *url = [NSURLfileURLWithPath:@"/Users/coohua/Desktop/bigIcon.png"];

// 2.创建供给

NSURLRequest *request=[NSURLRequestrequestWithURL:url];

// 3.加载央浼

[self.webView loadRequest:request];

  • 网页导航刷新有关函数

// 刷新

  • (void)reload;

//甘休加载

  • (void)stopLoading;

//后退函数

  • (void)goBack;

//前进函数

  • (void)goForward;

//是不是能够往退

@property (nonatomic,readonly, getter=canGoBack)BOOL canGoBack;

//是不是足以向前

@property (nonatomic,readonly, getter=canGoForward)BOOL canGoForward;

//是不是正在加载

@property (nonatomic,readonly, getter=isLoading)BOOL loading;

viewdidload中设置导航栏,leftBarButtonItem的设置图片,对应点击方法定义。

3 代理公约利用:UIWebViewDelegate

一共有多个点子

///是不是同意加载网页,也可获得js要开拓的url,通过截取此url可与js交互

  • (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    

    NSString *urlString = [[request URL] absoluteString];

    urlString = [urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    

    NSArray *urlComps = [urlString componentsSeparatedByString:@"://"];

    NSLog(@"urlString=%@---urlComps=%@",urlString,urlComps);

    returnYES;

}

///开端加载网页

  • (void)webViewDidStartLoad:(UIWebView *)webView {

    NSURLRequest *request = webView.request;

    NSLog(@"webViewDidStartLoad-url=%@--%@",[request URL],[request HTTPBody]);

}

///网页加载成功

  • (void)webViewDidFinishLoad:(UIWebView *)webView {

    NSURLRequest *request = webView.request;

    NSURL *url = [request URL];

    if ([url.path isEqualToString:@"/normal.html"]) {

        NSLog(@"isEqualToString");

    }

    NSLog(@"webViewDidFinishLoad-url=%@--%@",[request URL],[request HTTPBody]);

    NSLog(@"%@",[self.webView stringByEvaluatingJavaScriptFromString:@"document.title"]);

}

///网页加载错误

  • (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {

    NSURLRequest *request = webView.request;

    NSLog(@"didFailLoadWithError-url=%@--%@",[request URL],[request HTTPBody]);

    

}

BaseWKWebViewController

4 与js交互

///加载达成时调用

  • (void)webViewDidFinishLoad:(UIWebView *)webView

{

    [self.webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];

    

    [self.webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];

    

    [self.showView removeFromSuperview];

    NSString *jsToGetHTMLSource = @"document.getElementsByTagName('html')[0].innerHTML";

    NSString *HTMLSource = [self.webView stringByEvaluatingJavaScriptFromString:jsToGetHTMLSource];

    

    [self.activityView stopAnimating];

    

    NSRange range = [HTMLSource rangeOfString:@"Bad Gateway"];//判定字符串是或不是带有

    bool urlIsTrue = (range.location == NSNotFound);

    if (urlIsTrue ==true ) {

        range = [HTMLSource rangeOfString:@"Network is unreachable"];

        urlIsTrue = (range.location == NSNotFound);

    }

    if (urlIsTrue ==true ) {

        range = [HTMLSource rangeOfString:@"页面一纸空文"];

        urlIsTrue = (range.location == NSNotFound);

    }

    if (urlIsTrue ==true) {

        range = [HTMLSource rangeOfString:@"网页不能够访谈"];

        urlIsTrue = (range.location == NSNotFound);

    }

    if (urlIsTrue ==true) {

        range = [HTMLSource rangeOfString:@"Not Found"];

        urlIsTrue = (range.location == NSNotFound);

    }

    //网页可访谈遮盖大家温馨的回来开关

    if (urlIsTrue==true)

    {

        self.topView.hidden =YES;

    }

    else

    {

        [webView stopLoading];

        [self addShowView];

    } 

}

下一场自个儿的BaseWKWebViewController基于BaseViewController创制。在.h定义多少个参数代码如下:

三、WKWebView使用验证

/**

*@briefwkWebview

*/

@property (nonatomic, strong) WKWebView                *wkWebView;

/**

*@briefwkConfiguration配置

*/

@property (nonatomic, strong) WKWebViewConfiguration    *wkConfiguration;

/**

*@briefwebUrl

*/

@property (nonatomic, copy) NSString                    *urlString;

1 简单利用

与UIWebview同样,仅需三步:记住导入(#import <WebKit/WebKit.h>)

  • (void)simpleExampleTest {

    // 1.创办webview,并设置大小,"20"为状态栏高度

    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0,20,self.view.frame.size.width,self.view.frame.size.height -20)];

    // 2.创办央浼

    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"];

    // 3.加载网页

    [webView loadRequest:request];

    

    //最终将webView加多到分界面

    [self.view addSubview:webView];

}

本文由胜博发-编程发布,转载请注明来源:建议使用WKWebView替代UIWebViewsbf282.com,跳转之后拨