网络2-UIWebView

1.UIWebView

UIWebView不仅能加载网络资源还可以加载本地资源,目前支持的常用的文档格式如:html、pdf、docx、txt等。

UIWebView整个使用相当简单:创建URL->创建请求->加载请求,无论是加载本地文件还是Web内容都是这三个步骤。UIWebView内容加载事件同样是通过代理通知外界,常用的代理方法如开始加载、加载完成、加载出错等,这些方法通常可以帮助开发者更好的控制请求加载过程。

加载资源:

- (void)loadRequest:(NSURLRequest *)request;

常用的属性和方法:

//重新加载(刷新) 
- (void)reload;
//停⽌止加载    
- (void)stopLoading;
//回退     
- (void)goBack;
//前进    
- (void)goForward;
//需要进⾏检测的数据类型   
@property(nonatomic) UIDataDetectorTypes dataDetectorTypes 
//是否能回退 
@property(nonatomic,readonly,getter=canGoBack) BOOL canGoBack;
//是否能前进 
@property(nonatomic,readonly,getter=canGoForward) BOOL canGoForward; 
//是否正在加载中  
@property(nonatomic,readonly,getter=isLoading) BOOL loading;
//是否伸缩内容至适应屏幕当前尺寸 
@property(nonatomic) BOOL scalesPageToFit; 

遵守UIWebViewDelegate协议,监听UIWebView的加载过程:

//开始发送请求(加载数据)时调用:
- (void)webViewDidStartLoad:(UIWebView *)webView;
//请求完毕(加载数据完毕)时调⽤:
- (void)webViewDidFinishLoad:(UIWebView *)webView;
//请求错误时调用:
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;
//监听UIWebView的加载过程:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;

下面是一个例子:

在storyBoard中拖入如下控件:

searchBar的代理方法:

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self request:_searchBar.text];
    [searchBar resignFirstResponder];
}

加载searchBar中的请求:

-(void)request:(NSString *)urlStr{
    //创建url
    NSURL *url;
    
    //如果file://开头的字符串则加载bundle中的文件
    if([urlStr hasPrefix:kFILEPROTOCOL]){
        //取得文件名
        NSRange range= [urlStr rangeOfString:kFILEPROTOCOL];
        NSString *fileName=[urlStr substringFromIndex:range.length];
        url=[[NSBundle mainBundle] URLForResource:fileName withExtension:nil];
    }else if(urlStr.length>0){
        //如果是http请求则直接打开网站
        if ([urlStr hasPrefix:@"http"]) {
            url=[NSURL URLWithString:urlStr];
        }else{//如果不符合任何协议则进行搜索
            urlStr=[NSString stringWithFormat:@"http://m.bing.com/search?q=%@",urlStr];
        }
        urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//url编码
        url=[NSURL URLWithString:urlStr];
        
    }
    //创建请求
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    //加载请求页面
    [_webView loadRequest:request];
}

WebView的代理方法:

-(void)webViewDidStartLoad:(UIWebView *)webView{
    //显示网络请求加载
    [UIApplication sharedApplication].networkActivityIndicatorVisible=true;
}

-(void)webViewDidFinishLoad:(UIWebView *)webView{
    //隐藏网络请求加载图标
    [UIApplication sharedApplication].networkActivityIndicatorVisible=false;
    //设置按钮状态
    [self setBarButtonStatus];
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"error detail:%@",error.localizedDescription);
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"系统提示" message:@"网络连接发生错误!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alert show];
}

设置前进后退按钮:

-(void)setBarButtonStatus{
    if (_webView.canGoBack) {
        _barButtonBack.enabled=YES;
    }else{
        _barButtonBack.enabled=NO;
    }
    if(_webView.canGoForward){
        _barButtonForward.enabled=YES;
    }else{
        _barButtonForward.enabled=NO;
    }
}

运行结果如下:

你可以在这里下载到代码。

- (void)getAccessToken:(NSString *)requestToken
{
    [HttpTool postWithPath:@"oauth2/access_token" params:@{
       @"client_id" : kAppKey,
       @"client_secret" : kAppSecret,
       @"grant_type" : @"authorization_code",
       @"redirect_uri" : kRedirectURI,
       @"code" : requestToken
       } success:^(id JSON) {
           // 保存账号信息
           Account *account = [[Account alloc] init];
           account.accessToken = JSON[@"access_token"];
           account.uid = JSON[@"uid"];
           [[AccountTool sharedAccountTool] saveAccount:account];
           
           // 回到主页面
           ViewController *main = [[ViewController alloc]init];
           if (main) {
               [self presentViewController:main animated:YES completion:nil];
           }
       } failure:^(NSError *error) {
           
           
       }];
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • iOS开发系列--网络开发 概览 大部分应用程序都或多或少会牵扯到网络开发,例如说新浪微博、微信等,这些应用本身可...
    lichengjin阅读 3,721评论 2 7
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,246评论 4 61
  • AFNNetworking 2.0你相信你一定知道AFNNetworking,不知道你还可以看看该作者的博文,所以...
    瞎嘚嘚阅读 721评论 1 1
  • IOS之UIWebView的使用 刚接触IOS开发1年多,现在对于 混合式 移动端开发越来越流行,因为开发成本上、...
    学无止境666阅读 45,907评论 5 53
  • 启航的爸爸是个大学语文老师,母亲是国企职工,家境优渥。作为大学语文老师的爸爸,文学功底是很好的,所以启航的名字肯定...
    门里的太阳阅读 219评论 0 0