Reputation: 23
I am having trouble loading a local HTML file. Here is my code. please help.
let URL = NSBundle.mainBundle().pathForResource("index2", ofType: "html")
let request = NSURLRequest(URL: url!)
Webview.loadRequest(request)
by use the following code. I have manage to load the html file but it doesn't load up the CSS!
let htmlFile = NSBundle.mainBundle().pathForResource("index1", ofType: "html") let html = try? String(contentsOfFile: htmlFile!, encoding: NSUTF8StringEncoding) GSFWebView.loadHTMLString(html!, baseURL: nil)
Upvotes: 1
Views: 3921
Reputation: 11
I only had to add this code to the viewDidLoad method:
1- First of all, you have to get the local URL from the Bundle. (previously, I added the index.html file to the project, copying when asked)
2- Then you have to create the request URL to be loaded from the webView.
3- After all, add the new webView created as a subView from the main view.
That worked for me.
if let url = Bundle.main.url(forResource: "index", withExtension: "html"){// 1st step
webView.loadFileURL(url, allowingReadAccessTo: url)
let request = URLRequest(url: url as URL) // 2nd step
webView.load(request)
self.view.addSubview(self.webView) // 3rd step
}
Upvotes: 0
Reputation: 478
Simply write this code inside your ViewDidLoad i have added url of this page as example, just replace it with yours. On storyboard you don't need to do anything, if you have any extra view added on you view controller as container for website then replace self.view
in my code with your view.
let myWebView:UIWebView = UIWebView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
//add your url on line below
myWebView.loadRequest(URLRequest(url: URL(string: "https://stackoverflow.com/questions/26647447/load-local-html-into-uiwebview-using-swift")!))
self.view.addSubview(myWebView)
And if you want to load page from local file, you can do it by defining url this way.
Swift 2
let url = NSBundle.mainBundle().URLForResource("webFileName", withExtension:"html")
Swift 3
let url = Bundle.main.url(forResource: "webFileName", withExtension: "html")
Upvotes: 1