solero_ice
solero_ice

Reputation: 49

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

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

Answers (3)

Peter Hornsby
Peter Hornsby

Reputation: 4266


EDIT

  1. Get URL using NSFileManger instance method URLsForDirectory(inDomains:)

  2. Append the file name (myFile.html) to the URL we get back from NSFileManager

  3. Initialize a NSURLRequest object with the URL.

  4. Use the UIWebView or WKWebView class to load the request.


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

solero_ice
solero_ice

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

Adis
Adis

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

Related Questions