Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

iOS 開發:把本地檔案載入 UIWebView 的關鍵是「檔案 URL」

UIWebView 要顯示 App 內部的檔案,不能只丟一個路徑字串,必須先轉成 file:// 形式的 URL。以下示範從 Documents 目錄取檔並載入。

從 Documents 目錄載入

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                     NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:docName];

NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

self.myWebView.scalesPageToFit = YES;
[self.myWebView loadRequest:request];

scalesPageToFit 設為 YES 可讓寬度超出螢幕的內容自動縮放,閱讀 PDF 或排版較宽的 HTML 時相當實用。

若檔案來自 App bundle

打包在應用內的資源要用 mainBundle 取得路徑:

NSString *mainBundleDirectory = [[NSBundle mainBundle] bundlePath];
NSString *path = [mainBundleDirectory stringByAppendingPathComponent:docName];

要注意 bundle 內是唯讀的,若需要寫入或快取,仍應改用 Documents 或 Caches 目錄。另外,載入中文內容時請確認檔案編碼為 UTF-8,並在 HTML 標頭中正確宣告,否則容易出現亂碼。

Copyright © Linux教程網 All Rights Reserved