加载webView

来源:互联网 发布:淘宝单反四大黑店 编辑:程序博客网 时间:2024/05/29 07:00

1.创建UIWebView,为其配置request


UIWebView *webView = [[UIWebViewalloc]initWithFrame:CGRectMake(0,20,kScreenWidth,kScreenHeight)];

    NSURLRequest *request = [[NSURLRequestalloc]initWithURL:[NSURLURLWithString:@"http://write.blog.csdn.net/postlist"]];

    webView.delegate =self;

    [self.viewaddSubview:webView];

    [webView loadRequest:request];


2.在类中鉴定<UIWebVIewDelegate>,并设置代理为self



3.实现代理方法,用来检测 开始加载,加载完成,加载失败


- (void)webViewDidStartLoad:(UIWebView *)webView;  //开始加载

- (void)webViewDidFinishLoad:(UIWebView *)webView;  //加载完成

- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullableNSError *)error;  //加载失败


4.为了提升用户体验,由于网速的慢的原因,需要让用户知道此时是否正在加载


#pragma - mark webView的代理方法

- (void)webViewDidStartLoad:(UIWebView *)webView;{

    

      //创建UIActivityIndicatorView背底半透明View

    UIView *view = [[UIViewalloc]initWithFrame:self.view.frame];

    [view setTag:108];

    [view setBackgroundColor:[UIColorblackColor]];

    [view setAlpha:0.5];

    [self.viewaddSubview:view];

    

    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorViewalloc]initWithFrame:CGRectMake(0.0f,0.0f,32.0f, 32.0f)];

    [activityIndicator setCenter:view.center];

    [activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];

    activityIndicator.tag =102;

    [view addSubview:activityIndicator];

    

    [activityIndicator startAnimating];

    

    NSLog(@"webViewStartLoad");


    

}

- (void)webViewDidFinishLoad:(UIWebView *)webView;{

    

    UIActivityIndicatorView *activityIndicator = [self.viewviewWithTag:102];

    

    [activityIndicator stopAnimating];

    UIView *view = (UIView*)[self.viewviewWithTag:108];

    [view removeFromSuperview];

    NSLog(@"webViewDidFinishLoad");

    

}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullableNSError *)error;{

    

    UIActivityIndicatorView *activityIndicator = [self.viewviewWithTag:102];

    

    [activityIndicator stopAnimating];

    UIView *view = (UIView*)[self.viewviewWithTag:108];

    [view removeFromSuperview];

    

    NSLog(@"webViewdidFailLoad");


}




整理和参考容芳志的技术博客  http://blog.csdn.net/totogo2010/article/details/7686164


0 0