iOS笔记----网页控件WebView

What is this?

WebView控件可以加载本地HTML代码或者网络资源

使用方法

加载本地HTML文件(NSString)

  • 为同步加载方式
#pragma mark - *********** 加载本地HTML文件(NSString)
- (IBAction)testLoadHTMLString:(id)sender {

    NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSURL *bundleUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
    NSError *error = nil;

    NSString *html = [[NSString alloc] initWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:&error];
    if(error == nil){
        [self.webView loadHTMLString:html baseURL:bundleUrl];
    }
}

加载本地HTML文件(NSData)

  • 为同步加载方式
#pragma mark - *********** 加载本地HTML文件(NSData)
 - (IBAction)testLoadData:(id)sender {

    NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSURL *bundleUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
    NSError *error = nil;

    NSData *htmlData = [[NSData alloc] initWithContentsOfFile:htmlPath];

    if(error == nil){
        [self.webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:bundleUrl];
    }
}

请求网址

  • 为异加载方式
#pragma mark - *********** 请求网址
- (IBAction)testLoadRequest:(id)sender {

    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
    self.webView.delegate = self;
}

异步加载本地HTML

#pragma mark - *********** 请求网址
- (IBAction)testLoadLocalHttp:(id)sender {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];

    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]];
}

UIWebViewDelegate委托协定方法

  • WebView 将要加载页面
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    return YES;
}
  • WebView 开始加载页面
// WebView 开始加载页面
-(void)webViewDidStartLoad:(UIWebView *)webView{
    // TODO
}
  • WebView 页面加载完成
-(void)webViewDidFinishLoad:(UIWebView *)webView{
    NSLog(@"%@", [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"]);
}
  • WebView 页面加载失败
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    // TODO
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值