UIWebView全解

是iOS内置的浏览器控件,可以浏览网页、打开文档等 
能够加载html/htm、pdf、docx、txt等格式的文件 
系统自带的Safari浏览器就是通过UIWebView实现的

MIME的英文全称是“Multipurpose Internet Mail Extensions” 多用途互联网邮件扩展,是一个互联网标准,最早应用于电子邮件系统,后来应用到浏览器 
服务器通过说明多媒体数据的MIME类型,告诉浏览器发送的多媒体数据的类型,从而让浏览器知道接收到的信息哪些是MP3文件,哪些是Shockwave文件等等 
服务器将MIME标志符放入传送的数据中告诉浏览器使用哪种插件读取相关文件 
MIME类型能包含视频、图像、文本、音频、应用程序等数据

怎样获取MIMEType?

(NSString )MIMEType:(NSString )fileName
{
// 定义路径
NSString path = [[NSBundle mainBundle]pathForResource:fileName ofType:nil];
// 定义URL
NSURL url = [NSURL fileURLWithPath:path];
// 定义请求
NSURLRequest request = [NSURLRequest requestWithURL: url];
// 定义响应
NSURLResponse response = nil;

// 发送同步请求
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

NSLog(@“MIMEType is %@“, [response MIMEType]);

return [response MIMEType];
}

<!-- lang: cpp -->
-(NSString *)mimeType:(NSString *)fileName
{

NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:nil ];
// NSURL *url = [[NSURL alloc] initWithString:path];

NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLResponse *ressponse = nil ;
[NSURLConnection sendSynchronousRequest:request returningResponse:&ressponse error:nil];
return [ressponse MIMEType];
// NSURL url = [[NSBundle mainBundle] URLForResource:fileName withExtension:nil];
//
// // 2. request
// NSURLRequest request = [NSURLRequest requestWithURL:url];
//
// // 3. 同步连接
// NSURLResponse *response = nil;
//
// [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
//
// // 4. 获得mimetyp
// return response.MIMEType;
}

// 测试加载HTML字符串
NSString *html = @“Hello

Hello Itcast

“;
[_webView loadHTMLString:html baseURL:nil];

// 测试加载部分HTML字符串,不需要显示整个网页内容时,通常使用此方法
NSString *partHtml = @“

Hello Itcast

“;
[_webView loadHTMLString:partHtml baseURL:nil];

// 测试加载本地PDF,需要指定MIMETYPE
[webView loadData:[NSData dataWithContentsOfFile:dataPath] MIMEType:@“application/pdf” textEncodingName:@“UTF-8” baseURL:nil];
// 测试加载本地文本文件,需要指定MIMETYPE

[webView loadData:[NSData dataWithContentsOfFile:dataPath] MIMEType:@“text/plain” textEncodingName:@“UTF-8” baseURL:nil];

// 测试网络HTML文件,需要指定MIMETYPE

NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle]resourcePath] isDirectory:YES];
[_webView loadData:[NSData dataWithContentsOfFile:dataPath] MIMEType:@“text/html” textEncodingName:@“UTF-8” baseURL:baseURL];

说明:baseURL是基准URL,程序要用到其他资源的位置

// 网页开始加载的时候调用

(void)webViewDidStartLoad:(UIWebView *)webView
// 网页加载完成的时候调用

(void)webViewDidFinishLoad:(UIWebView *)webView
// 网页加载出错的时候调用

(void)webView:(UIWebView )webView didFailLoadWithError:(NSError )error
// 网页中的每一个请求都会被触发这个方法,返回NO代表不执行这个请求(常用于JS与iOS之间通讯)

(BOOL)webView:(UIWebView )webView shouldStartLoadWithRequest:(NSURLRequest )request navigationType:(UIWebViewNavigationType)navigationType

原文地址:https://www.cnblogs.com/wcLT/p/4765463.html