WKWebView Get Started

WKWebView vs UIWebView

I am a SDK developer. And our SDK uses hybrid style (Native + Web)

UIWebView is useful because cookie sync automatically, cache clear is simple(Only 1 API, other APIs are covered which WKWebView does not have. (until iOS 11)

But, UIWebView has a lot of problem, no longer to maintain, has a lot of crash when the page is loaded, not secure.

So, this is the reason Apple recommend to

And UIWebView is now deprecated for several years. Many vendors tried to switch from UIWebView to WKWebView.

General application to load web is quite simple. Easy to switch. There are no reason to keep using UIWebView.

Finally, Apple decided not to accept UIWebView App : https://developer.apple.com/news/?id=12232019b

UIWebView 2019

From 2016?, after several years WKWebView comes, UIWebView becomes deprecated, but still existed and not reject from Apple

For iOS13, still alive as deprecated UI

WKWebView Get Started

To use WKWebView, we need to import WebKit.framework in our project.

Over XCode 10, interface builder supports WKWebView (In the past, we need to write source code to use WKWebView)

WebKit View is WKWebView.

Load

Let’s start simple use for WKWebView

There are 4 types of load method in WKWebView

  • Load HTML using URL
  • Load HTML string
  • Load HTML file from File path
  • Load HTML data from Data object

Example

This is storyboard.

Add Web View and Toolbar (some buttons on)

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {
    
    @IBOutlet weak var webView: WKWebView!  // interface builder 10.x

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
 
       // webView.loadHTMLString(<#T##string: String##String#>, baseURL: <#T##URL?#>)
       // webView.loadFileURL(<#T##URL: URL##URL#>, allowingReadAccessTo: <#T##URL#>)
       // webView.load(<#T##data: Data##Data#>, mimeType: <#T##String#>, //characterEncodingName: <#T##String#>, baseURL: <#T##URL#>)
        self.load(urlStr: "https://www.google.com")
       // self.loadContent(html: "<html><body><h2>Hello</h2></body></html>")
        
        webView.navigationDelegate = self
        webView.uiDelegate = self
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
    }
    
    private func load(urlStr: String) {
        guard let url = URL(string: urlStr) else { return }
        let request = URLRequest(url: url)
        webView.load(request)
    }
    
    private func loadContent(html: String) {
        webView.loadHTMLString(html, baseURL: nil)
    }
}

Test first 2 way to load. load method is just to load URL, loadContent loads string HTML.

iOS
スポンサーリンク
Professional Programmer2

コメント