使用KVO观察WKWebView的URL属性在iOS 10中不起作用 [英] using KVO to observe WKWebView's URL property not work in iOS 10

查看:247
本文介绍了使用KVO观察WKWebView的URL属性在iOS 10中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用WKWebView加载网页.当用户单击网页中的按钮时,我的网页将打开一个自定义架构网址(例如asfle://download?media_id = 1).和 我使用KVO观察WKWebView的URL属性以获取URL.它在iOS 9中很好用,但在iOS 10中不起作用.我无法获取该URL.我使用的是Xcode 8,Swift 2.3.

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 observe WKWebView's URL property to get the URL. It works well in iOS 9, but it doesn't work in iOS 10. I can't get the url. I use Xcode 8, swift 2.3.

override func viewDidLoad() {
        super.viewDidLoad()

        webView.addObserver(self, forKeyPath: "URL", options: .New, context: nil)
    }

override func observeValueForKeyPath(keyPath: String?,
                                  ofObject object: AnyObject?,
                                           change: [String : AnyObject]?,
                                                  context: UnsafeMutablePointer<Void>)
    {
        print("url:\(webView.URL)")
    }

在iOS 9中,它可以打印网址.但是在iOS 10中,仅会打印网站的url,当用户触摸网页中的按钮时,不会打印任何内容.

In iOS 9, it can print url. But in iOS 10 only the website's url get printed, when user touch the button in webpage, nothing get printed.

推荐答案

您仍然可以观察WKWebViewurl属性,只需确保对返回的观察值保持强烈的引用即可:

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")")
        })
    }
}

此外,如果您打算在观察封闭中使用self作为weak,请不要忘记将其捕获,否则您将获得一个保留周期.

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.

这篇关于使用KVO观察WKWebView的URL属性在iOS 10中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆