20

我正在尝试Estimated Progress在我WKWebView的中实施,但似乎无法弄清楚。你能帮我吗?

这是我所拥有的:

self.view = self.webView;

NSURL *url = [NSURL URLWithString:stringWeb];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];

self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];

[self.webView loadRequest:request];

我看到这个答案有点意思,但那是一个微调器:UIWebView with Progress Bar

Apple 记录了某种文件estimatedProgress(我假设导航栏正下方的蓝色细条显示了 Safari 中的进度),但我一般不知道如何实现:https ://developer.apple.com /library/ios/documentation/WebKit/Reference/WKWebView_Ref/#//apple_ref/occ/instp/WKWebView/estimatedProgress

所以我被困在这里。任何帮助将不胜感激,谢谢!

更新这就是我现在所拥有的。出现崩溃是因为我的 Progress View 和 WKWebView 似乎加载了两次,我不确定为什么会这样。收到需要删除观察者的错误。这是我的代码 -

视图控制器.h

@interface WebPageViewController : UIViewController <UIWebViewDelegate>
@property (strong, nonatomic) NSString *stringMobile;
@property (strong, nonatomic) NSString *stringWeb;
@property (strong, nonatomic) IBOutlet UIView *view;
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic) UIProgressView *progressView;

视图控制器.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:self.webView];

    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];

    self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    self.progressView.center = self.view.center;
    [self.view addSubview:self.progressView];

    NSURLRequest *URLRequest = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:stringWeb]];
    [self.webView loadRequest:URLRequest];


}

- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];

    // if you have set either WKWebView delegate also set these to nil here
    [self.webView setNavigationDelegate:nil];
    [self.webView setUIDelegate:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"] && object == self.webView) {
        [self.progressView setAlpha:1.0f];
        [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];
    }
}

更新:使用 CocoaPods 这就是我所拥有的,但它显示了两个视图而不是一个 webview

- (void)viewDidLoad {
    [super viewDidLoad];
    NSURL *myURL = [NSURL URLWithString: [self.url stringByAddingPercentEscapesUsingEncoding:
                                          NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:myURL];
    //[self.webView loadRequest:request];

    // KIN
    // Deleted UIWebView in Storyboard
    KINWebBrowserViewController *webBrowser = [[KINWebBrowserViewController alloc] init];
    [self.navigationController pushViewController:webBrowser animated:YES];
    [webBrowser loadURL:myURL];
}
4

3 回答 3

59

检查GitHub 上的KINWebBrowser以查看以下解决方案的完整实现。

如果您仔细查看您链接到的estimatedProgress属性的文档WKWebView,您会看到:

The WKWebView class is key-value observing (KVO) compliant for this property.

这意味着您可以在属性上设置键值观察estimatedProgress以观察其值的变化。通过该observeValueForKeyPath方法,您可以更新您的 UI。

Cocoa 中的 KVO 设计模式非常混乱。查看这篇优秀的 NSHipster 文章,了解Key Value Observing的最佳实践。

estimatedProgress这是on的 KVO 实现WKWebView

从你的UIViewController,设置你的WKWebView并添加自己作为观察者estimatedProgress

    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:self.webView];

    [self.webView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:NSKeyValueObservingOptionNew context:NULL];

在同一UIViewController设置您的observeValueForKeyPath方法来过滤estimatedProgresswebView. 然后,您可以直接访问该estimatedProgress值并相应地更新您的 UI。

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.webView) {
        NSLog(@"%f", self.webView.estimatedProgress);
        // estimatedProgress is a value from 0.0 to 1.0
        // Update your UI here accordingly
    }
    else {
        // Make sure to call the superclass's implementation in the else block in case it is also implementing KVO
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

确保从UIViewControllerUIViewController 的 dealloc 方法中删除 KVO。isViewLoaded如果尚未添加观察者,检查是否避免崩溃很重要。

- (void)dealloc {

    if ([self isViewLoaded]) {
        [self.wkWebView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
    }

    // if you have set either WKWebView delegate also set these to nil here
    [self.wkWebView setNavigationDelegate:nil];
    [self.wkWebView setUIDelegate:nil];
}

要在一些大文件上看到这一点,请加载这个甜蜜星系的巨大图像文件。(此文件为 35MB。请确保您使用的是 WiFi!)

    NSURLRequest *URLRequest = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.spacetelescope.org/static/archives/images/large/opo0328a.jpg"]];
    [self.webView loadRequest:URLRequest];

如果您使用的是UIProgressView,您可以使用以下代码实现类似 Safari 的淡出效果:

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

        if(self.wkWebView.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];
    }
}
于 2014-10-05T03:31:11.380 回答
27

斯威夫特式:

@IBOutlet weak var progressView: UIProgressView!

//...

func viewDidLoad() {
    webView.addObserver(self, forKeyPath: "estimatedProgress", options: .New, context: nil) // add observer for key path
}

// ...

override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
    if (keyPath == "estimatedProgress") { // listen to changes and updated view
        progressView.hidden = webView.estimatedProgress == 1
        progressView.setProgress(Float(webView.estimatedProgress), animated: true)
    }
}

斯威夫特 3 更新:

// Add Observer in viewDidLoad
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") { // listen to changes and updated view
            progress.isHidden = webView.estimatedProgress == 1
            progress.setProgress(Float(webView.estimatedProgress), animated: false)
        }
}


Also please make sure to implement "WKNavigationDelegate" and add webview reference navigationDelegate to self like below

webView.navigationDelegate=self
于 2015-06-25T11:47:30.490 回答
4

Swift 3.2及更高版本:

private var progressKVOhandle: NSKeyValueObservation?
@IBOutlet weak var progressView: UIProgressView!
// ...

override func viewDidLoad() {
    super.viewDidLoad()

    // ...

    progressKVOhandle = webView.observe(\.estimatedProgress) { [weak self] (object, _) in
        self?.progressView.setProgress(Float(object.estimatedProgress), animated: true)
    }
}
于 2018-04-16T15:58:19.080 回答