iOS 网页进度条 NJKWebViewProgress

APP 访问网页时,经常会见到一个进度条,如图所示:
iOS 网页进度条 NJKWebViewProgress_第1张图片

NJKWebViewProgress 可以很好的实现这个效果,使用方法也很简单:
1. 实例化 NJKWebViewProgress
2. 设置代理 UIWebViewDelegateNJKWebViewProgressDelegate
3. 实现代理方法。

  • 初始化
UIWebView *webView;
NJKWebViewProgressView *_progressView;
NJKWebViewProgress *_progressProxy;

webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height-62]; //初始化宽高
[self.view addSubview: webView];
[webView setScalesPageToFit:YES]; //自适应
  • 设置代理
_progressProxy = [[NJKWebViewProgress alloc] init];
webView.delegate = _progressProxy;
_progressProxy.webViewProxyDelegate = self;
_progressProxy.progressDelegate = self;

代理方法:

  • 更新显示条进度
- (void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress {
    [_progressView setProgress:progress animated:YES];
}
progressProxy.progressBlock = ^(float progress) {
    [progressView setProgress:progress animated:NO];
};
  • 页面加载完成
- (void)webViewDidFinishLoad:(UIWebView *)webView;
  • 页面加载失败
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;
  • 关闭进度条
// 页面加载完成和失败的时候关闭进度条
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  • 可以通过 progress 和一个给定的常量比较,来决定文档的当前状态
-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    if (progress == NJKInteractiveProgressValue) {
        // The web view has finished parsing the document,
        // but is still loading sub-resources
    }
}

// 给定的几个常量如下:
const float NJKInitialProgressValue = 0.1f;
const float NJKInteractiveProgressValue = 0.5f;
const float NJKFinalProgressValue = 0.9f;

其他方法:

  • 配置链接地址
- (void)getUrl {
    NSString *url  = [[NSString alloc]init];
    url = @"https://www.baidu.com/";
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; //状态栏左边显示网络活动标志
    [self loadData:url]; //加载数据
}
  • 加载数据
- (void)loadData:(NSString *)url {
    NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [webView loadRequest:request];
}
  • 清除浏览器缓存
- (void)removeCookies {
    NSHTTPCookieStorage *cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray *pcookies = [cookies cookiesForURL:[NSURL URLWithString:preUrl]];
    for (NSHTTPCookie *cookie in pcookies) {
        [cookies deleteCookie:cookie];
    }
}

GitHub 链接:https://:.com/ninjinkun/NJKWebViewProgress

你可能感兴趣的:(iOS,开源框架)