簡體   English   中英

迅速將html文件從ios上的文檔目錄加載到UIWebview

[英]load html file to UIWebview from documents directory on ios with swift

我有一個html文件和其他html使用的文件(css,.png)保存在documents目錄中。如何使用swift將這個html文件加載到UIWebView或wkwebview中?我在Objective-c中找到了一些示例,但是很快就什么都沒有。我對objective-c一無所知。

let path=getCurrenttHtmlStartPage()
var hContent = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding) 
webView!.loadHTMLString(hContent, baseURL: nil)
webView!.hidden=false 

路徑是文檔文件夾中的路徑。 /Users/pmdevios/Library/.../Documents/Content/Html/index.html。

用這種方法html中的其他文件不顯示(images),所以我想用這樣的另一種方法

webView!.loadFileURL(path, allowingReadAccessToURL: path)

使用以下代碼,它起作用了!

let filePath = (folder as  NSString).stringByAppendingPathComponent(_currentHtmlStartPage!)
var url:NSURL=NSURL(fileURLWithPath:filePath)
var request:NSURLRequest=NSURLRequest(URL:url)
webView!.loadRequest(request)

文件夾:字符串,表示文檔文件夾_currentHtmlStartPage:文件名的字符串(例如index.html)中的路徑


編輯

  1. 使用NSFileManger實例方法URLsForDirectory(inDomains:)獲取URL

  2. 將文件名(myFile.html)附加到我們從NSFileManager獲得的URL

  3. 使用URL初始化NSURLRequest對象。

  4. 使用UIWebViewWKWebView類加載請求。


let fileManager = NSFileManager.defaultManager()
var URL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
URL = URL.URLByAppendingPathComponent("myFile.html")

let request = NSURLRequest(URL: fileURL)
webView.loadRequest(request)

在我的頭頂上:

if let fileURL = NSBundle.mainBundle().URLForResource("myFile", withExtension: "html") {
    let request = NSURLRequest(URL: fileURL)
    webView.loadRequest(request)
}

在html和css文件中,您將需要一個平坦的目錄結構,因為這就是它們最終在應用程序中的方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM