网页的跳转

2017-01-10  本文已影响19人  陈水寒

跳转web界面有4种方式
1、 直接跳转Safari浏览器:有刷新、后退、进度条等;
2、 UIWebView:没有控制按钮,需要自己增加;
3、 UISafariViewController:在IOS9 中苹果增加了UISafariViewController,效果同Safari;
4、 WKWebView:在IOS8中 UIWebView的升级版;

UISafariViewController的使用

需要在控制器中导入头文件<SafariServices/SafariServices.h>,然后在需要跳转的代码中实现以下代码即可:

NSURL *url = [NSURL URLWithString:urlStr];
SFSafariViewController *safariVC = [[SFSafariViewController alloc] initWithURL:urlStr];
// 官方推荐使用modal方式跳转,返回就不需要自己处理,如果使用push还需要自己添加代理处理返回按钮
[self presentViewController:safariVC animated:YES completion:nil];

效果如下:

safariViewController跳转效果.gif

WKWebView的使用:

  1. 在控制器中导入头文件<WebKit/WebKit.h>
  2. 在以下位置添加库文件


    图片.png

需要自己添加几个前进、后退、刷新按钮,然后通过KVO读取WKWebView相关属性信息即可,关键代码如下:

a) 在控制器中添加观察者,观察webview的键值变化

    WKWebView *webView = [[WKWebView alloc] init];
    _webView = webView;
    [self.contentView addSubview:webView];
    
    // 发送请求
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:_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:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];

b) KVO事件处理

\\ 移除观察者
- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"canGoBack"];
    [self.webView removeObserver:self forKeyPath:@"canGoForward"];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"title"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    self.goBack.enabled = self.webView.canGoBack;// 后退按钮
    self.forword.enabled = self.webView.canGoForward;// 前进按钮
    self.progressView.progress = self.webView.estimatedProgress; // 进度条
    self.progressView.hidden = self.webView.estimatedProgress >= 1; // 加载完成后隐藏进度条
    self.title = self.webView.title; // 网页标题
}

c) 按钮点击时调用

- (IBAction)goBackClick:(id)sender {
    [self.webView goBack];
}
- (IBAction)forwordClick:(id)sender {
    [self.webView goForward];
}
- (IBAction)refreshClick:(id)sender {
    [self.webView reload];
}

最终效果如下:

WKWebView效果.gif
上一篇 下一篇

猜你喜欢

热点阅读