UIWebView加载Html

作者: FlyElephant | 来源:发表于2016-05-16 17:00 被阅读1161次

苹果自带的UIWebView提供了基本的Html访问功能,提供了三种方法:
<pre><code>`

  • (void)loadRequest:(NSURLRequest *)request;
  • (void)loadHTMLString:(NSString *)string baseURL:(nullable NSURL *)baseURL;
  • (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL;`</code></pre>

加载本地Html

方式1:
<pre><code>`
NSString *resourcePath = [[NSBundle mainBundle] resourcePath];

NSString *filePath =[resourcePath stringByAppendingPathComponent:@"FlyElephant.html"];

NSMutableString *htmlstring=[[NSMutableString alloc] initWithContentsOfFile:filePath  encoding:NSUTF8StringEncoding error:nil];
NSURL *baseUrl=[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];

[self.webView loadHTMLString:htmlstring baseURL:baseUrl];`</code></pre>

方式2:
<pre><code>`

NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Book" ofType:@"html"];
NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
[self.webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:filePath]];`</code></pre>

加载网络Html

通过loadRequest实现:
<pre><code>`

NSURL *url = [[NSURL alloc] initWithString:@"https://www.baidu.com/"];
[self.webView loadRequest:[NSURLRequest requestWithURL:url]];`</code></pre>

加载NSData

loadData使用起来也非常简单:
<pre><code>`
NSString *path = [[NSBundle mainBundle]pathForResource:@"Book.pdf" ofType:nil];

//以二进制的形式加载数据
NSData *data = [NSData dataWithContentsOfFile:path];

[self.webView loadData:data MIMEType:@"application/pdf" textEncodingName:@"UTF-8" baseURL:nil];`</code></pre>

友情提示,如果是新建项目,注意在info.list中添加NSAppTransportSecurity为Dictionary
,NSAllowsArbitraryLoads为Boolean:


FlyElephant.png

相关文章

网友评论

    本文标题:UIWebView加载Html

    本文链接:https://www.haomeiwen.com/subject/rymbrttx.html