UIWebView全解
UIWebView是iOS內置的瀏覽器控件,可以瀏覽網頁、打開文檔等能夠加載html/htm、pdf、docx、txt等格式的文件。
是iOS內置的瀏覽器控件,可以瀏覽網頁、打開文檔等
能夠加載html/htm、pdf、docx、txt等格式的文件
系統自帶的Safari瀏覽器就是通過UIWebView實現的
MIME的英文全稱是“Multipurpose Internet Mail Extensions” 多用途互聯網郵件擴展,是一個互聯網標準,最早應用于電子郵件系統,后來應用到瀏覽器
服務器通過說明多媒體數據的MIME類型,告訴瀏覽器發送的多媒體數據的類型,從而讓瀏覽器知道接收到的信息哪些是MP3文件,哪些是Shockwave文件等等
服務器將MIME標志符放入傳送的數據中告訴瀏覽器使用哪種插件讀取相關文件
MIME類型能包含視頻、圖像、文本、音頻、應用程序等數據
怎樣獲取MIMEType???
// 獲得本地文件的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];
</li> </ul>
}mydemo
-(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 = @“HelloHello 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