iOS: WKWebView Vs UIWebView

2019-01-27 03:01发布

问题:

I've an app/project with deployment target version - iOS 10.

I had used UIWebView, which is deprecated now and replaced by WKWebView. So, I want to replace UIWebView with WKWebView in my project also.

It force me to either use UIWebView (with iOS 10) or change deployment target to iOS 11.

I cannot change deployment target but as a middleware solution, I added code (programatically) support for both. I mean, if user's device OS is iOS 11 (or above) then use WKWebView else use UIWebView (for iOS 10 or below).

Issue statement: Storyboard's view controller does not support both versions, I mean, in storyboard, if I set View controller's deployment target to iOS 11 then app crashes in iOS 10 (and obvious it should) and if I set view controller's deployment target to iOS 10, then storyboard does not allow me to build project.

For iOS 10, WKWebView shows me this error: Xcode 9 GM - WKWebView NSCoding support was broken in previous versions

Question: How can I make storyboard (View controller) to use WKWebView for iOS 11 and UIWebView for iOS 10? Is there any configuration setup or option in story board (view controller) that can allow me to add both interface outlets?

回答1:

You can simply create and add a WKWebView via code.

If you want a visual representation for layout purposes in your Storyboard, here is one way to do it.

Add a standard UIView in your view controller in your Storyboard. This will act as a "holder" for your web view. Connect it to an IBOutlet, then in viewDidLoad add an instance of WKWebView as a subview of that "holder" view.

class MyViewController: UIViewController, WKNavigationDelegate {

    // standard UIView, added in Storyboard
    @IBOutlet weak var webViewHolder: UIView!

    // instance of WKWebView
    let wkWebView: WKWebView = {
        let v = WKWebView()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()

    override func viewDidLoad() {

        super.viewDidLoad()

        // add the WKWebView to the "holder" UIView
        webViewHolder.addSubview(wkWebView)

        // pin to all 4 edges
        wkWebView.topAnchor.constraint(equalTo: webViewHolder.topAnchor, constant: 0.0).isActive = true
        wkWebView.bottomAnchor.constraint(equalTo: webViewHolder.bottomAnchor, constant: 0.0).isActive = true
        wkWebView.leadingAnchor.constraint(equalTo: webViewHolder.leadingAnchor, constant: 0.0).isActive = true
        wkWebView.trailingAnchor.constraint(equalTo: webViewHolder.trailingAnchor, constant: 0.0).isActive = true

        // load a URL into the WKWebView
        if let url = URL(string: "https://google.com") {
            wkWebView.load(URLRequest(url: url))
        }

        // from here on out, use wkWebView just as if you had added it in your storyboard

    }

}