iOS开发之给webView添加进度条

视图dealloc需要取消观察

- (void)dealloc

{

    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];

}

// 通过监听estimatedProgress可以获取它的加载进度 还可以监听它的title ,URL, loading

- (void)viewDidLoad {

    [super viewDidLoad];

    // 设置背景颜色

    self.view.backgroundColor = BgColor;

    // 通过监听estimatedProgress可以获取它的加载进度 还可以监听它的title ,URL, loading

    [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];

 }

 

#pragma mark -- 根据不同的url,创建webView

- (void)CreateWebViewWithURL:(NSString*)strUrl{

    if (_webView == nil) {

        // 1)创建WebView

        _webView = [[IMYWebView alloc] initWithFrame:CGRectMake(0, 0, Kwidth, Kheight-64)];

        // 2)设置代理

        _webView.delegate = self;

        _webView.scalesPageToFit = YES;

        _webView.scrollView.bounces = NO;

    }

    // 3)设置URL地址

    NSURL *url = [NSURL URLWithString:strUrl];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    [request addValue:[self readCurrentCookie] forHTTPHeaderField:@"Cookie"];

    [_webView loadRequest:request];

    [self.view addSubview:_webView];

    // 4)创建加载进度条

    if (self.progressView == nil) {

        self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, Kwidth, 5)];

        self.progressView.progress = 0;

    }

    [self.view addSubview:self.progressView];

}

 

#pragma mark -- 监听加载进度

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{

    if ([keyPath isEqualToString:@"estimatedProgress"]) {

        [self.progressView setProgress:_webView.estimatedProgress animated:YES];

    }

    if (object == _webView && [keyPath isEqualToString:@"estimatedProgress"]) {

        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];

        if (newprogress == 1) {

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

                self.progressView.hidden = YES;

                [self.progressView setProgress:0 animated:NO];

            });

        }else {

            self.progressView.hidden = NO;

            [self.progressView setProgress:newprogress animated:YES];

        }

    }

}

 

posted on 2016-11-10 16:54  程序“猿”  阅读(256)  评论(0)    收藏  举报

导航