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];
}