- 大家都知道,使用UIWebView加载本地或远程服务器上的网页,sdk提供了三个加载接口:
- - (void)loadRequest:(NSURLRequest *)request;
- - (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL;
- - (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL;
- - (void)loadRequest:(NSURLRequest *)request;
- 这个接口一般用于加载url所指定的某个远程服务器网页,其实它也能用来加载本地网页资源。
- //加载远程网页
- [self.myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]];
- //加载本地网页
- NSString *filePath = [[NSBundle mainBundle] pathForResource:@"kline71" ofType:@"html" inDirectory:@"XiangJie"];
- [self.myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
- 注意:网页可能会使用其他的如图片资源,css样式文件,loadRequest会在网页的当前目录下(如本例中的XiangJie目录下查找)
- - (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL;
- 这个接口用于直接加载html代码。如果html直接写在了代码中,推荐使用这种方法。当然你也可以先从本地读取html代码,然后加载。请注意baseURL地址目录要正确,否则html中引用的资源是找不到的。
- NSString *filePath = [[NSBundle mainBundle] pathForResource:@"kline71" ofType:@"html" inDirectory:@"XiangJie"];
- NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
- NSString *baseURL = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"XiangJie/img"];
- [_myWebView loadHTMLString:htmlString baseURL:[NSURL URLWithString:baseURL]];
- - (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL;
- 这个接口用于加载html文件。MIMEType值一般为"text/html"。同样,请注意baseURL地址目录要正确,否则html中引用的资源是找不到的。
- NSString *filePath = [[NSBundle mainBundle] pathForResource:@"kline71" ofType:@"html" inDirectory:@"XiangJie"];
- NSData *data = [NSData dataWithContentsOfFile:filePath];
- NSString *baseURL = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"XiangJie/img"];
- [self.myWebView loadData:data MIMEType:@"text/html" textEncodingName:@"utf-8" baseURL:[NSURL URLWithString:baseURL]];
UIWebView加载本地或远程服务器上的网页--初识
最新推荐文章于 2021-06-07 18:22:43 发布