2018-03-23

WKWebView基类封装

项目一直使用UIWebView,相关基类方法封装使用比较完善,业务量重,想整体替换为WKWebView有点难度,需要时间完善。所以我在自己的demo中初步封装了WKWebView,参考原有的项目的UIWebView。

BaseViewController

由于后续导航栏返回事件需要处理,自定义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;

            }

        }

    }

}

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

BaseWKWebViewController

然后我的BaseWKWebViewController基于BaseViewController创建。在.h定义几个参数代码如下:

/**

*@briefwkWebview

*/

@property (nonatomic, strong) WKWebView                *wkWebView;

/**

*@briefwkConfiguration配置

*/

@property (nonatomic, strong) WKWebViewConfiguration    *wkConfiguration;

/**

*@briefwebUrl

*/

@property (nonatomic, copy) NSString                    *urlString;

对应的webView,wkWebView一些属性设置值,加载url的地址。

然后在.m中创建webView,其中有一点需要注意:方法重名问题。当初我再父类BaseViewController中和BaseWKWebView中都用setUpUi这个方法,结果父类的方法就失效了,被子类覆盖了。所以子类创建视图的方法调整为setBaseWK,具体代码如下:

- (void)viewDidLoad {

    [super viewDidLoad];

    [self setBaseWK];

}

- (void)setBaseWK{

    if (!self.wkConfiguration) {

        self.wkConfiguration = [[WKWebViewConfiguration alloc]init];

        //设置一些属性

    }

    self.wkWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) configuration:self.wkConfiguration];

    self.wkWebView.UIDelegate = self;

    self.wkWebView.navigationDelegate = self;

    self.wkWebView.allowsBackForwardNavigationGestures = YES;

    [self.view addSubview:self.wkWebView];

    [self.wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString]]];

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

}

创建WKWebView,设置它的两个代理:UIDelegate和navigationDelegate。代理方法稍后再讲。allowsBackForwardNavigationGestures这个属性是控制webView侧滑返回的,默认是NO,设置为YES后,web页面能像原生页面一样策划返回了。然后将webView加到当前视图,加载对应的url地址。最后是网上看到的方法,利用KVO设置WKWebView的title,相比较UIWebView的设置这个有一丝繁琐,具体代码稍后提及。

UIDelegate

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

在这个方法中写如下代码:

if (!navigationAction.targetFrame.isMainFrame) {

        [webView loadRequest:navigationAction.request];

    }

    return nil;

WKNavigationDelegate

这个代理里面写了三个方法:

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

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

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

didFinishNavigation就是完成加载webView时候的方法。后面两个对应UIWebView中的shouldLoad,将要加载方法。WK中分为请求发起前即navigationAction和接口请求相应后navigationResponse。对面方法下面允许加载,不然url不会跳转。

KVO设置WKWebView的title

代码如下:

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

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

        if (object == self.wkWebView) {

            self.title = self.wkWebView.title;

        }else {

            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];

        }

    }else {

        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];

    }

}

- (void)dealloc{

    [self.wkWebView removeObserver:self forKeyPath:@"title"];

}

注意在dealloc中移除KVO。

返回问题

重写父类的backButton方法:

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

    if ([self.wkWebView canGoBack]) {

        [self.wkWebView goBack];

    }else {

        [self.navigationController popViewControllerAnimated:YES];

    }

}

当web页面多次进入跳转新页面后,为了防止逐级返回,参考老项目做了close按钮操作。当判断当前页面是要做回退跳转的时候,在左上角增加关闭当前web控制器的按钮。代买如下:

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

    if (navigationAction.navigationType == WKNavigationTypeBackForward) {

        [self addCloseItemAction];

    }

- (void)addCloseItemAction{

    if (self.navigationItem.leftBarButtonItems.count<2) {


        UIButton* closeButton = [UIButton buttonWithType:UIButtonTypeCustom];


        [closeButton setImage:[UIImage imageNamed:@"title_new_close"] forState:UIControlStateNormal];

        closeButton.frame = CGRectMake(0, 0, 30, 30);

        [closeButton addTarget:self action:@selector(closeWeb) forControlEvents:UIControlEventTouchUpInside];


        UIBarButtonItem* closeBarItem = [[UIBarButtonItem alloc] initWithCustomView:closeButton];


        self.navigationItem.leftBarButtonItems = @[self.navigationItem.leftBarButtonItem,closeBarItem];

    }

}

- (void)closeWeb{

    [self.navigationController popToRootViewControllerAnimated:YES];

}

这样返回操作就得到了优化。

WKTestWebViewController

最后我用WKTestWebViewController基于WKWebViewController创建相关web页面对之前代码进行校验,返现能够跳转,但是在WKTestWebViewController中如果再写UIDelegate和NavigationDelegate的时候,发现父类的方法又被覆盖了,所以将父类实现的wk代理方法代理出来。对WKWebViewController做操作:在.h中添加代理,对应.m实现代码如下:

.h添加代理

@protocol GFWKWebViewDelegate;

@interface BaseWKWebViewController : BaseViewController

/**

*@briefGFwkWebDelegate

*/

@property (nonatomic, weak) id    wkWebDelegate;

@end

@protocol GFWKWebViewDelegate

@optional

//wkUIDelegate

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

//wkNavigationDelegate

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

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

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

@end

.m实现代理

UIDelegate

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

    if (self.wkWebDelegate && [self.wkWebDelegate respondsToSelector:@selector(GF_webView:createWebViewWithConfiguration:forNavigationAction:windowFeatures:)]) {

        [self.wkWebDelegate GF_webView:webView createWebViewWithConfiguration:configuration forNavigationAction:navigationAction windowFeatures:windowFeatures];

    }

NavigationDelegate

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

    if (self.wkWebDelegate && [self.wkWebDelegate respondsToSelector:@selector(GF_webView:didFinishNavigation:)]) {

        [self.wkWebDelegate GF_webView:webView didFinishNavigation:navigation];

    }

}

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


    if (self.wkWebDelegate && [self.wkWebDelegate respondsToSelector:(@selector(GF_webView:decidePolicyForNavigationAction:decisionHandler:))]) {

        [self.wkWebDelegate GF_webView:webView decidePolicyForNavigationAction:navigationAction decisionHandler:decisionHandler];

    }

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

    decisionHandler(WKNavigationResponsePolicyAllow);

    if (self.wkWebDelegate && [self.wkWebDelegate respondsToSelector:@selector(GF_webView:decidePolicyForNavigationResponse:decisionHandler:)]) {

        [self.wkWebDelegate GF_webView:webView decidePolicyForNavigationResponse:navigationResponse decisionHandler:decisionHandler];

    }

}

这样四个方法都实现了,其实只要实现子类用到的方法就好了。当然如果父类在做统一设置,实现了相关wk代理的方法,需要后续再完善。

代理使用

在WKTestWebViewController使用父类设置的代理,头文件中引入代理,设置代理等于self,对应代理方法调整,代码如下:

@interface WKTestWebViewController ()

@end

@implementation WKTestWebViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    [self setTestWK];

}

- (void)setTestWK{

    self.wkWebDelegate = self;

}

#pragma mark GFWKWebView UIDelegate

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

    NSLog(@"%ld", (long)navigationAction.navigationType);

//    decisionHandler(WKNavigationActionPolicyAllow);

}

注意子类代理方法中不能在写decisionHandler(WKNavigationActionPolicyAllow),不然报错重复decisionHandler。这样就能在实现父类返回关闭功能以及未来需要统一增加的功能同时,还能完成具体子类个性化处理。

总结

如上就是我对WKWebView相关认识,期间的父类子类重名问题卡了一段时间,后续功能方法的优化需要再实践中逐步完善。

你可能感兴趣的:(2018-03-23)