Reputation: 49
I have an html file and other files that html uses(css,.png) that is saved in the documents directory.How can I load this html file in a UIWebView or wkwebview using swift?I have found some examples in objective-c but nothing in swift.I don't know anything about objective-c..
let path=getCurrenttHtmlStartPage()
var hContent = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
webView!.loadHTMLString(hContent, baseURL: nil)
webView!.hidden=false
Path is the path in documents folder. /Users/pmdevios/Library/.../Documents/Content/Html/index.html.
With this way the other files inside html aren't showing(images) so I want to do it with another way like this
webView!.loadFileURL(path, allowingReadAccessToURL: path)
Upvotes: 1
Views: 5890
Reputation: 4266
EDIT
Get URL using NSFileManger instance method URLsForDirectory(inDomains:)
Append the file name (myFile.html) to the URL we get back from NSFileManager
Initialize a NSURLRequest object with the URL.
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)
Upvotes: 1
Reputation: 49
With the below code it worked!
let filePath = (folder as NSString).stringByAppendingPathComponent(_currentHtmlStartPage!)
var url:NSURL=NSURL(fileURLWithPath:filePath)
var request:NSURLRequest=NSURLRequest(URL:url)
webView!.loadRequest(request)
folder:string that represents the path in the documents folder _currentHtmlStartPage:string of file's name (e.g. index.html)
Upvotes: 2
Reputation: 4552
Of the top of my head:
if let fileURL = NSBundle.mainBundle().URLForResource("myFile", withExtension: "html") {
let request = NSURLRequest(URL: fileURL)
webView.loadRequest(request)
}
You'll need a flat directory structure in your html and css files because that's how they end up in the app.
Upvotes: 0