Swift如何监控WKWebView页面加载进度?

How to monitor WKWebView page load progress in Swift?

这是我的代码:

@IBOutlet weak var webView: WKWebView!
@IBOutlet weak var progressView: UIProgressView!

override func viewDidLoad() {
    super.viewDidLoad()

    webView.uiDelegate = self
    webView.navigationDelegate = self

    webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)        
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if (keyPath == "estimatedProgress") {
        progressView.setProgress(Float(webView.estimatedProgress), animated: true)
        print(webView.estimatedProgress)
    }
}

但 estimatedProgress 仅显示两个浮点数(0.1 和 1.0),我认为它不起作用。我使用了 Alamofire 进度,它以毫秒为单位进行更改,这使我的 UI 变得更好,但是这段代码无法正常工作...

有谁能帮我看看 webView 的进度吗?

Swift 4.0

@IBOutlet weak var webView: WKWebView!
@IBOutlet weak var progressView: UIProgressView!
override func viewDidLoad() {
    super.viewDidLoad()

    // load website or HTML page
    self.webView.load(NSURLRequest(url: URL(string: "https://www.apple.com")!) as URLRequest);

    //add observer to get estimated progress value
    self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil);
}

// Observe value
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "estimatedProgress" {
        print(self.webView.estimatedProgress);
        self.progressView.progress = Float(self.webView.estimatedProgress);
    }
}

新Swift KVO 方法

class ViewController: UIViewController {

    private lazy var webView = WKWebView()
    private var observation: NSKeyValueObservation?

    override func viewDidLoad() {
        super.viewDidLoad()

        observation = webView.observe(\WKWebView.estimatedProgress, options: .new) { _, change in
            print("Loaded: \(change)")
        }
    }

    deinit {
        self.observation = nil
    }
}

这应该在 Swift 上正常工作 5:

@IBOutlet weak var webView: WKWebView!
@IBOutlet weak var progressView: UIProgressView!

private var observation: NSKeyValueObservation? = nil

override func viewDidLoad() {
    super.viewDidLoad()

    // load website or HTML page
    webView.load(NSURLRequest(url: URL(string: "https://www.apple.com")!) as URLRequest)

    // add observer to update estimated progress value
    observation = webView.observe(\.estimatedProgress, options: [.new]) { _, _ in
        self.progressView.progress = Float(self.webView.estimatedProgress)
    }
}

deinit {
    observation = nil
}

Objective-C KVO 实现:

-(void)viewDidLoad {
    [super viewDidLoad];
    [self.webView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:NSKeyValueObservingOptionNew context:NULL];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.webView) {
         self.progressView.alpha = 1.0;
         [self.progressView setProgress:self.webView.estimatedProgress animated:YES];

         if(self.webView.estimatedProgress >= 1.0f) {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
               [self.progressView setAlpha:0.0f];
             } completion:^(BOOL finished) {
               [self.progressView setProgress:0.0f animated:NO];
            }];
         }

    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

这个在Swift 5、先导入WebKit,然后

//
// ViewController.swift
//

@IBOutlet weak var webView: WKWebView!
@IBOutlet weak var progressView: UIProgressView!

override func viewDidLoad() {
    super.viewDidLoad()

    webView.uiDelegate = self
    webView.navigationDelegate = self

    // Change it here
    webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)        
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if (keyPath == "estimatedProgress") {
        // Also change it here
        progressView.progress = Float(webView.estimatedProgress)
        print(webView.estimatedProgress)
    }
}

希望对你有用!