WKWebView-使用WebKit载入网页

代码基于Swift4.0
官方文档对 WKWebView 描述,官方推荐我们使用WKWebView而不要使用 UIWebView
Starting in iOS 8.0 and OS X 10.10, use WKWebView to add web content to your app. Do not use UIWebView or WebView.

WKWebView特点:

  1. 在性能、稳定性、功能方面有很大提升;
  2. 允许JavaScript的Nitro库加载并使用(UIWebView中限制);
  3. 支持了更多的HTML5特性;
  4. 高达60fps的滚动刷新率以及内置手势;
  5. 将UIWebViewDelegate与UIWebView重构成了14类与3个协议

使用WKWebView的小例子

import UIKit
import WebKit

class ViewController: UIViewController{
    
    var webView: WKWebView!
    
    override func loadView() {
        //创建网页加载的偏好设置
        let prefrences = WKPreferences()
        prefrences.javaScriptEnabled = false
        
        //配置网页视图
        let webConfiguration = WKWebViewConfiguration()
        webConfiguration.preferences = prefrences
        
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.navigationDelegate = self;
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let myURL = URL(string: "https://www.apple.com")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
    }

}

// MARK: WKNavigationDelegate
extension ViewController: WKNavigationDelegate {
    //视图开始载入的时候显示网络活动指示器
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
    }
    
    //载入结束后,关闭网络活动指示器
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
    }
    
    //阻止链接被点击(.cancel 自身不加载,.allow运行加载)
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if navigationAction.navigationType == .linkActivated {
            decisionHandler(.cancel)
            
            let alertController = UIAlertController(title: "Action not allowed", message: "Tapping on links is not allowed. Sorry!", preferredStyle: .alert)
            alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            present(alertController, animated: true, completion: nil)
            return
            
        }
        
        decisionHandler(.allow)
    }
}


你可能感兴趣的:(WKWebView-使用WebKit载入网页)