WKWebView估计进度

时间:2014-10-05 00:00:14

标签: ios webview uiwebview wkwebview

我正在尝试在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

苹果公司记录了某种estimatedProgress(我假设它的导航栏正下方的蓝色条形图显示了Safari中的进展),但我一般不会看到如何实现:{ {3}}

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

更新这就是我现在所拥有的。因为看起来我的进度视图和WKWebView加载了两次而导致崩溃,我不确定为什么会这样。获得需要删除观察者的错误。这是我的代码 -

ViewController.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;

ViewController.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];
}

3 个答案:

答案 0 :(得分:51)

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

如果仔细查看与您关联的estimatedProgress WKWebView属性的文档,您会看到:

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

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

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

以下是estimatedProgressWKWebView的KVO实施:

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方法,以过滤掉estimatedProgress的{​​{1}}属性。然后,您可以直接访问webView值并相应地更新您的用户界面。

estimatedProgress

确保从该UIViewController的dealloc方法中的- (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]; } } 中删除KVO。如果尚未添加观察者,请检查是否UIViewController以避免崩溃。

isViewLoaded

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

- (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];
}

如果你使用的是 NSURLRequest *URLRequest = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.spacetelescope.org/static/archives/images/large/opo0328a.jpg"]]; [self.webView loadRequest:URLRequest]; ,你可以使用以下代码实现淡出效果之类的游览:

UIProgressView

答案 1 :(得分: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)
    }
}

Swift 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

答案 2 :(得分:1)

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