WebView网页三种不同的数据加载请求方法

1 创建WebView

UIWebView * webView=[[UIWebView alloc]initWithFrame:self.view.bounds];
    webView.delegate=self;
    [self.view addSubview:webView];

2 加载请求

1>>加载URL请求

NSURL * url=[[NSBundle mainBundle]URLForResource:@"login" withExtension:@"html"];//本地文件
//NSURL * url=[[NSURL URLWithString:@"http//:baidu.com"]];//网址
    NSURLRequest * request=[NSURLRequest requestWithURL:url];
    [webView loadRequest:request];

2>>加载String请求

NSString * path=[[NSBundle mainBundle]pathForResource:@"login" ofType:@"html"];
    NSString * string=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    [webView loadHTMLString:string baseURL:nil];

3>>data请求

 //--获取当前文件的类型
    NSString * path=[[NSBundle mainBundle]pathForResource:@"hell" ofType:@"pdf"]
    NSURLRequest * request=[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
    NSURLResponse * response;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
  //--获取数据
    NSData * data=[NSData dataWithContentsOfFile:path];
    [webView loadData:data MIMEType:response.MIMEType textEncodingName:@"utf8" baseURL:nil];

3 实现UIWebViewDelegate代理

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{

    //在网页加载前执行,确定是否进入网页
    NSString * path=request.URL.absoluteString;//绝对路径
    NSInteger location=[path rangeOfString:@"baidu"].location;
    if (location != NSNotFound) {
        return NO;
    }
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView{
//    NSLog(@"webViewDidStartLoad");
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    //判断webView是否可以返回或前进
    self.back.enabled=webView.canGoBack;
    self.go.enabled=webView.canGoForward;
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"===%@",error);
}

4 实现网页前进后退

- (void)backAction{
    //执行返回行为
    [self.webView goBack];
}

- (void)goAction{
    //执行前进行为
    [self.webView goForward];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值