WKWebView

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

    // 跳转界面 push 展示网页

    /*

        1.Safari openURL :自带很多功能(进度条,刷新,前进,倒退等等功能),必须要跳出当前应用

        2.UIWebView (没有功能) ,在当前应用打开网页,并且有safari,自己实现,UIWebView不能实现进度条

        3.SFSafariViewController:专门用来展示网页 需求:即想要在当前应用展示网页,又想要safari功能 iOS9才能使用

         3.1 导入#import <SafariServices/SafariServices.h>

     

        4.WKWebView:iOS8 (UIWebView升级版本,添加功能 1.监听进度 2.缓存)

            4.1 导入#import <WebKit/WebKit.h>

     

     */

    // 创建网页控制器

    LZJSquareItem *item = self.squareItems[indexPath.row];

    if (![item.url containsString:@"http"]) return;

    

    LZJWebViewController *webVc = [[LZJWebViewController alloc] init];

    webVc.url = [NSURL URLWithString:item.url];

    [self.navigationController pushViewController:webVc animated:YES];

    

}

 

 

 

 

 

 

 

 

 

#pragma mark - 生命周期方法

- (void)viewDidLayoutSubviews

{

    [super viewDidLayoutSubviews];

    

    _webView.frame = self.contentView.bounds;

}

 

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.

    // 添加webView

    WKWebView *webView = [[WKWebView alloc] init];

    _webView = webView;

    [self.contentView addSubview:webView];

    

    // 展示网页

    NSURLRequest *request = [NSURLRequest requestWithURL:_url];

    [webView loadRequest:request];

    

    // KVO监听属性改变

    /*

        Observer:观察者

        KeyPath:观察webView哪个属性

        options:NSKeyValueObservingOptionNew:观察新值改变

     

        KVO注意点.一定要记得移除

     */

    [webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:nil];

    [webView addObserver:self forKeyPath:@"canGoForward" options:NSKeyValueObservingOptionNew context:nil];

    [webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];

    

    // 进度条

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

    

}

 

// 只要观察对象属性有新值就会调用

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context

{

    self.backItem.enabled = self.webView.canGoBack;

    self.forwardItem.enabled = self.webView.canGoForward;

    self.title = self.webView.title;

    self.progressView.progress = self.webView.estimatedProgress;

    self.progressView.hidden = self.webView.estimatedProgress >= 1;

}

 

#pragma mark - 对象被销毁

- (void)dealloc

{

    [self.webView removeObserver:self forKeyPath:@"canGoBack"];

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

    [self.webView removeObserver:self forKeyPath:@"canGoForward"];

    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];

}

原文地址:https://www.cnblogs.com/liuzhenjie/p/5289723.html