WKWebView简单使用总结

最近公司有做APP中嵌套 H5的业务;鉴于WKWebView的性能优于UIWebView,所以就选择了WKWebView。WKWebView在使用的过程中,遇到一些问题,这里我就做了一下总结,跟大家分享一下。

一. 基本使用

引入头文件#import <WebKit/WebKit.h>

1> 初始化

- (WKWebView *)webView{

              if (!__webView) {

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

               config.selectionGranularity = WKSelectionGranularityDynamic;

               config.allowsInlineMediaPlayback = YES;

               WKPreferences *preferences = [WKPreferences new];

                //是否支持JavaScript

               preferences.javaScriptEnabled = YES;

               //不通过用户交互,是否可以打开窗口

              preferences.javaScriptCanOpenWindowsAutomatically = YES;

             config.preferences = preferences;

            _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight - 64) configuration:config];

             [self.view addSubview:_webView];

          _webView.navigationDelegate = self;

          _webView.UIDelegate = self;

       }

      return _webView;

}

/* 加载服务器url的方法*/

- (void)setURL:(NSString*)URL {

        _URL= URL;

      //  NSString *url = @"https://www.baidu.com";

       NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URL]];

       [_webView loadRequest:request];

}

WKWebViewConfiguration和WKPreferences中有很多属性可以对webview初始化进行设置,这里就不一一介绍了。

2> 遵循的协议和实现的协议方法:

#pragma mark - 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{


}

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

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

    //允许跳转

    decisionHandler(WKNavigationActionPolicyAllow);

    //不允许跳转

    //decisionHandler(WKNavigationActionPolicyCancel);

}

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

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


    NSLog(@"%@",navigationResponse.response.URL.absoluteString);

    //允许跳转

    decisionHandler(WKNavigationResponsePolicyAllow);

    //不允许跳转

    //decisionHandler(WKNavigationResponsePolicyCancel);

}

3>下面介绍几个开发中需要实现的小细节:

1、url中文处理

有时候我们加载的URL中可能会出现中文,需要我们手动进行转码,但是同时又要保证URL中的特殊字符保持不变,那么我们就可以使用下面的方法(方法放到了NSString中的分类中):

- (NSURL *)url{

#pragma clang diagnostic push

#pragma clang diagnostic ignored"-Wdeprecated-declarations"

    return [NSURL URLWithString:(NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]", NULL,kCFStringEncodingUTF8))];

#pragma clang diagnostic pop

}

2、获取h5中的标题 3、添加进度条

获取h5中的标题和添加进度条放到一起展示看起来更明朗一点,在初始化wenview时,添加两个观察者分别用来监听webview 的estimatedProgress和title属性:

webview.navigationDelegate = self;

webview.UIDelegate = self;


[webview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];

[webview addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];

添加创建进度条,并添加进度条图层属性:

@property (nonatomic,weak) CALayer *progressLayer;

-(void)setupProgress{

    UIView *progress = [[UIView alloc]init];

    progress.frame = CGRectMake(0, 0, KScreenWidth, 3);

    progress.backgroundColor = [UIColor  clearColor];

    [self.view addSubview:progress];


    CALayer *layer = [CALayer layer];

    layer.frame = CGRectMake(0, 0, 0, 3);

    layer.backgroundColor = [UIColor greenColor].CGColor;

    [progress.layer addSublayer:layer];

    self.progressLayer = layer;

}

实现观察者的回调方法:

#pragma mark - KVO回馈

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{

    if ([keyPath isEqualToString:@"estimatedProgress"]) {

        self.progressLayer.opacity = 1;

        if ([change[@"new"] floatValue] <[change[@"old"] floatValue]) {

            return;

        }

        self.progressLayer.frame = CGRectMake(0, 0, KScreenWidth*[change[@"new"] floatValue], 3);

        if ([change[@"new"]floatValue] == 1.0) {

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

                self.progressLayer.opacity = 0;

                self.progressLayer.frame = CGRectMake(0, 0, 0, 3);

            });

        }

    }else if ([keyPath isEqualToString:@"title"]){

        self.title = change[@"new"];

    }

}


4、添加userAgent信息

有时候H5的伙伴需要我们为webview的请求添加userAgent,以用来识别操作系统等信息,但是如果每次用到webview都要添加一次的话会比较麻烦,下面介绍一个一劳永逸的方法。

在Appdelegate中添加一个WKWebview的属性,启动app时直接,为该属性添加userAgent:

- (void)setUserAgent {

    _webView = [[WKWebView alloc] initWithFrame:CGRectZero];

    [_webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {

        if (error) { return; }

        NSString *userAgent = result;

        if (![userAgent containsString:@"/mobile-iOS"]) {

            userAgent = [userAgent stringByAppendingString:@"/mobile-iOS"];

            NSDictionary *dict = @{@"UserAgent": userAgent};

            [TKUserDefaults registerDefaults:dict];

        }

    }];

}

这样一来,在app中创建的webview都会存在我们添加的userAgent的信息。

二.iOS 原生JS交互

在WKWebView中实现与JS的交互还需要实现另外一个代理方法:WKScriptMessageHandler

#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController

      didReceiveScriptMessage:(WKScriptMessage *)message

在 message的name和body属性中我们可以获取到与H5(JS)调取原生的方法名和所传递的参数。

1> H5(JS)中要写的方法:

window.webkit.messageHandlers.theMethodOfCallingOC.postMessage({

                    "picType": "0",

                    "picCount":"9";

                })

        }

theMethodOfCallingOC,需要OC 实现的方法, message中传的是参数;

注意:H5(JS)只能向原生传递一个参数,所以如果有多个参数需要传递,可以让H5(JS)传递对象或者JSON字符串即可。

2> OC调用H5(JS)方法

[webview evaluateJavaScript:“JS语句” completionHandler:^(id _Nullable data, NSError * _Nullable error) {

 }];

我们举例使用一下

首先,遵循代理:

注册方法名:

config.preferences = preferences;

WKUserContentController *user = [[WKUserContentController alloc]init];

[user addScriptMessageHandler:self name:@"theMethodOfCallingOC"];

config.userContentController =user;

实现代理方法:

#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController

      didReceiveScriptMessage:(WKScriptMessage *)message{

       NSLog(@"方法名:%@", message.name);

       NSLog(@"参数:%@", message.body);

        // 方法名

        NSString *methods = [NSString stringWithFormat:@"%@:", message.name];

        SEL selector =NSSelectorFromString(methods);

        // 调用方法

        if([selfrespondsToSelector:selector]) {

            [selfperformSelector:selectorwithObject:message.body];

        }else{

            NSLog(@"未实行方法:%@", methods);

        }

}

- (void)theMethodOfCallingOC:(NSString*)message{

}

最后需要删除掉注册的方法

- (void)dealloc{

    //这里需要注意,前面增加过的方法一定要remove掉。

   [_webView.configuration.userContentController removeScriptMessageHandlerForName:@"theMethodOfCallingOC"];

}

but,但是我无意间发现自从注册了"theMethodOfCallingOC"方法后,控制器一直释放不了.

[_webView.configuration.userContentController   addScriptMessageHandler:self name:@"theMethodOfCallingOC"];

看了半天,将这个 self改成弱引用还是释放不了,具体原因不太清楚,还有待研究,欢迎一起探讨;

解决方案:

.h

#import<UIKit/UIKit.h>

#import<WebKit/WebKit.h>

@protocol WKDelegate

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

@end

@interface WKDelegateViewController : UIViewController

@property (weak , nonatomic) id delegate;

@end

.m

#import "WKDelegateViewController.h"

@interface WKDelegateViewController ()

@end

@implementationWKDelegateViewController

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

    if([self.delegaterespondsToSelector:@selector(userContentController:didReceiveScriptMessage:)]) {

        [self.delegate userContentController:userContentController didReceiveScriptMessage:message];

    }

}

@end


具体实现:

(一)遵守协议<WKDelegate>

(二)定义全局变量

@property(nonatomic,strong)WKUserContentController* userContentController;

(三)初始化

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

        self.userContentController = [[WKUserContentController alloc] init];

        configuration.userContentController=self.userContentController;

        //注册方法

        WKDelegateViewController * delegateController = [[WKDelegateViewController alloc] init];

        delegateController.delegate=self;

        [self.userContentControlleraddScriptMessageHandler:delegateController  name:@"theMethodOfCallingOC"];

 configuration.preferences= preferences;

        WKWebView*h5webView = [[WKWebViewalloc]initWithFrame:webBoundsconfiguration:configuration];

(四)最后销毁

- (void)dealloc{

    //这里需要注意,前面增加过的方法一定要remove掉。

    [self.userContentController removeScriptMessageHandlerForName:@"theMethodOfCallingOC"];

}

OK,可以释放了,哪里有不对的,请多多指教.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,233评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,013评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,030评论 0 241
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,827评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,221评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,542评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,814评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,513评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,225评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,497评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,998评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,342评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,986评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,812评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,560评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,461评论 2 266

推荐阅读更多精彩内容

  • WKWebView在实际开发中的使用汇总 最近公司的项目中大量使用了webview加载H5,鉴于WKWebView...
    许何健阅读 561评论 0 0
  • WKWebView.14年就出来了.用的少.并不是很熟练.听说性能比UIWebView好很多.将内核啥的集成了.....
    侭情显現阅读 2,295评论 2 2
  • WKWebView基类封装 项目一直使用UIWebView,相关基类方法封装使用比较完善,业务量重,想整体替换为W...
    IntMan阅读 350评论 0 0
  • 因为项目需要,需要原生页面和h5交互调用,WKWebView提供了非常丰富的代理方法,参考了各位大神的详解,记录下...
    longkingwdlsky阅读 606评论 0 0
  • 先祝大家新年快乐!在2015年的最后一天,晒着太阳跷二郎腿,突然手痒想写点什么;然而本月书评又一时半会憋不出来(我...
    灯泡小队长阅读 320评论 0 1