using KVO to observe WKWebView's URL property not work in iOS 10

前端 未结 3 893
太阳男子
太阳男子 2021-01-06 02:52

I use WKWebView to load my webpage. When user click a button in webpage, my webpage will open a custom schema URL (e.g. asfle://download?media_id=1). And I use KVO to obser

3条回答
  •  孤街浪徒
    2021-01-06 03:27

    You can still observe WKWebView's url property, just be sure to hold a strong reference to the returned observation:

    class ViewController: UIViewController {
        var webView: WKWebView!
        var urlObservation: NSKeyValueObservation?
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // ...Initialize web view.
            webView = WKWebView(frame: view.bounds, configuration: WKWebViewConfiguration())
            webView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
            view.addSubview(webView)
    
            // Add observation.
            urlObservation = webView.observe(\.url, changeHandler: { (webView, change) in
                NSLog("Web view URL changed to \(webView.url?.absoluteString ?? "Empty")")
            })
        }
    }
    

    Also, don't forget to capture self as weak in observation closure if you plan to use it there, as otherwise you will get a retain cycle.

提交回复
热议问题