网页控件UIWebView 可以加载本地HTML代码或者网络资源。
通过Xcode创建简单的工程
storyboard上放这几个控件
.h文件
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIWebView *webView;
- (IBAction)testLoadHTMLString:(UIButton *)sender;
- (IBAction)testLoadData:(UIButton *)sender;
- (IBAction)testLoadRequest:(UIButton *)sender;
@end
.m文件
#import "ViewController.h"
@interface ViewController ()<UIWebViewDelegate>
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//第一种方法 通过html字符串加载数据 加载本地html
- (IBAction)testLoadHTMLString:(UIButton *)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]; //将字符集指定为 NSUTF8StringEncoding
if(error == nil){
[self.webView loadHTMLString:html baseURL:bundleUrl]; //从当前路径加载html文件
}
}
//第二种方法 加载本地html
- (IBAction)testLoadData:(UIButton *)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];
}
}
//第三种方法 异步加载 通过协议实现 UIWebViewDelegate 加载网络资源
- (IBAction)testLoadRequest:(UIButton *)sender {
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"]; //遵循http协议 指定请求的网站
NSURLRequest *request = [NSURLRequest requestWithURL:url]; //获取NSURLRequest对象
[self.webView loadRequest:request]; //发起异步请求网络
self.webView.delegate = self;
}
#pragma mark -UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView{
//加载完成调用的方法
NSLog(@"加载完成!");
NSLog(@"%@",[webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"]); //得到JavaScript语句
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
}
//-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
//{
//
//}
@end