iOS UIWebView 加载进度条的使用-WKWebView的使用,更新2017.6.26

1、由于项目中加载网络插件,直接使用了webview加载。使用了三方NJKWebViewProgress进度条的使用,近期在测试时发现,网络缓慢时出现白屏,有卡顿现象。

于是采用了WKWebView进行加载,KVO监听下载进度

//  ViewController.m

#import "ViewController.h"

#import 
#import 

#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)

#define IPHONEHIGHT(b) [UIScreen mainScreen].bounds.size.height*((b)/1334.0)
#define IPHONEWIDTH(a) [UIScreen mainScreen].bounds.size.width*((a)/750.0)

static void *WkwebBrowserContext = &WkwebBrowserContext;
@interface ViewController ()
{
    UIButton * back;
    UILabel * labeltitle;//webview显示前的title
    
}
@property (nonatomic, strong) WKWebView *wkWebView;
//设置加载进度条
@property (nonatomic,strong) UIProgressView *progressView;
@end


@implementation ViewController


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden= NO;
    [[UIApplication sharedApplication]setStatusBarHidden:YES];
    
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBar.hidden= NO;
    [[UIApplication sharedApplication]setStatusBarHidden:NO];
    
    [self.wkWebView.configuration.userContentController removeScriptMessageHandlerForName:@"WXPay"];
    [self.wkWebView setNavigationDelegate:nil];
    [self.wkWebView setUIDelegate:nil];
    
    //清除缓存
    [[NSURLCache sharedURLCache] removeCachedResponseForRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:
                                                                                              @"https://www.baidu.com"]]]; }

- (void)viewDidLoad { [super viewDidLoad]; [self CreatUI]; }
-(void)CreatUI{ self.view.backgroundColor = [UIColor blackColor];
    [self.wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]]]; //添加到主控制器上
    
    [self.view addSubview:self.wkWebView];
    //添加进度条
    [self.view addSubview:self.progressView];
//    
//    back = [myButton buttonWithType:UIButtonTypeCustom frame:CGRectMake(ScreenWidth-IPHONEWIDTH(120), ScreenHeight-IPHONEHIGHT(100), IPHONEWIDTH(50), IPHONEHIGHT(50)) tag:1 image:@"ic_history_ct_return" andBlock:^(myButton *button) {
//        
//        [self.navigationController popViewControllerAnimated:YES];
//        
//        
//    }];
//    
//    [self.view addSubview:back];
//    
    
        labeltitle = [[UILabel alloc] initWithFrame:CGRectMake(0, IPHONEHIGHT(15), self.view.bounds.size.width, IPHONEHIGHT(50))];
        //设置成绿色
        labeltitle.backgroundColor = [UIColor blackColor];
        labeltitle.text =@"Title";
    
        labeltitle.textColor = [UIColor whiteColor];
        labeltitle.font = [UIFont boldSystemFontOfSize:IPHONEHIGHT(35)];
        labeltitle.textAlignment = NSTextAlignmentCenter;
    
        [self.view addSubview:labeltitle];
    
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
}


#pragma mark ================ WKNavigationDelegate ================

//这个是网页加载完成,导航的变化
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
        [labeltitle removeFromSuperview];
//    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    
}

//开始加载
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    //开始加载的时候,让加载进度条显示
    self.progressView.hidden = NO;
    
}

//内容返回时调用
-(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{}

//服务器请求跳转的时候调用
-(void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{}


// 内容加载失败时候调用
-(void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    NSLog(@"页面加载超时");
//    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
//    [MBProgressHUD showText:@"加载失败,请重试" HUDAddedTo:self.view animated:YES afterDelay:1.5];
}

//跳转失败的时候调用
-(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{}

//进度条
-(void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{}


//KVO监听进度条
- (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];
        BOOL animated = self.wkWebView.estimatedProgress > self.progressView.progress;
        [self.progressView setProgress:self.wkWebView.estimatedProgress animated:animated];
        
        // Once complete, fade out UIProgressView
        if(self.wkWebView.estimatedProgress >= 1.0f) {
            [UIView animateWithDuration:0.3f delay:0.3f 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];
    }
}


#pragma mark ================ 懒加载 ================

- (WKWebView *)wkWebView{
    if (!_wkWebView) {
        //设置网页的配置文件
        WKWebViewConfiguration * Configuration = [[WKWebViewConfiguration alloc]init];
        //允许视频播放
        Configuration.allowsAirPlayForMediaPlayback = YES;
        // 允许在线播放
        Configuration.allowsInlineMediaPlayback = YES;
        // 允许可以与网页交互,选择视图
        Configuration.selectionGranularity = YES;
        // web内容处理池
        Configuration.processPool = [[WKProcessPool alloc] init];
        //自定义配置,一般用于 js调用oc方法(OC拦截URL中的数据做自定义操作)
        WKUserContentController * UserContentController = [[WKUserContentController alloc]init];
        // 添加消息处理,注意:self指代的对象需要遵守WKScriptMessageHandler协议,结束时需要移除
        [UserContentController addScriptMessageHandler:self name:@"WXPay"];
        // 是否支持记忆读取
        Configuration.suppressesIncrementalRendering = YES;
        // 允许用户更改网页的设置
        Configuration.userContentController = UserContentController;
        _wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:Configuration];
        _wkWebView.backgroundColor = [UIColor blackColor];
        // 设置代理
        _wkWebView.navigationDelegate = self;
        _wkWebView.UIDelegate = self;
        //kvo 添加进度监控
        [_wkWebView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:WkwebBrowserContext];
        //开启手势触摸
        _wkWebView.allowsBackForwardNavigationGestures = YES;
        // 设置 可以前进 和 后退
        //适应你设定的尺寸
        [_wkWebView sizeToFit];
    }
    return _wkWebView;
}


- (UIProgressView *)progressView{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
        
        _progressView.frame = CGRectMake(0, IPHONEHIGHT(20), self.view.bounds.size.width, IPHONEHIGHT(3));
        
        // 设置进度条的色彩
        [_progressView setTrackTintColor:[UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0]];
        _progressView.progressTintColor = [UIColor greenColor];
    }
    return _progressView;
}


//注意,观察的移除
-(void)dealloc{
    [self.wkWebView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
}




@end

 

 

 

 

 

 

 

 

 

不建议采用下方代码,会在网络缓慢时有白屏现象

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

1/拖到自己的?

2/ 这是 原文介绍的步骤。。但是再加入后,背景回短暂的绿色,我自己是想不要那个闪一下的状态

#import "InspectionReportViewController.h"

#import "NJKWebViewProgressView.h"
#import "NJKWebViewProgress.h"


@interface InspectionReportViewController ()
{
    UIWebView *webview;

    NJKWebViewProgressView *_progressView;
    NJKWebViewProgress *_progressProxy;
    
}
@end

@implementation InspectionReportViewController



-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
  //页面结束 去掉 视图
    [_progressView removeFromSuperview];
}

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

   
    webview = [[UIWebView alloc] initWithFrame:self.view.bounds];
    webview.backgroundColor = [UIColor blackColor];
    
    [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.baidu.com]]]];

    webview.scalesPageToFit = YES;

    webview.scrollView.scrollEnabled = NO;

    [self.view addSubview:webview];
    
    
    _progressProxy = [[NJKWebViewProgress alloc] init];
    webview.delegate = _progressProxy;
    _progressProxy.webViewProxyDelegate = self;
    _progressProxy.progressDelegate = self;
   
    CGFloat progressBarHeight = 2.f;
    CGRect navigationBarBounds = 
self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0, navigationBarBounds.size.height - progressBarHeight-IPHONEHIGHT(40), navigationBarBounds.size.width, progressBarHeight);

    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    
    [webview addSubview:_progressView];

  
}

//代理方法
#pragma mark - NJKWebViewProgressDelegate
-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    [_progressView setProgress:progress animated:YES];
    
}

 

3/ 。在 下面这个问价中?下面?

NJKWebViewProgressView.m 

 

//在这个方法中修改一下
-(void)configureViews{

 UIColor *tintColor = [UIColor ClearColor]; // iOS7 Safari bar color

}


//第二时这个方法中的改变 。在第二行

- (void)setProgress:(float)progress animated:(BOOL)animated
{
    BOOL isGrowing = progress > 0.0;


 //下面这个方法是加进去的   
_progressBarView.backgroundColor = [UIColor colorWithRed:22.f / 255.f green:126.f / 255.f blue:251.f / 255.f alpha:1.0]; ;
    

 

转载于:https://www.cnblogs.com/xujiahui/p/6617956.html

你可能感兴趣的:(iOS UIWebView 加载进度条的使用-WKWebView的使用,更新2017.6.26)