您的位置:首页 > 移动开发

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

2016-04-28 19:50 316 查看

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
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: