Load local html into UIWebView using swift

IosSwiftUiwebview

Ios Problem Overview


This one is driving me crazy early this morning. I want to load some local html into a web view:

class PrivacyController: UIViewController {
    
    @IBOutlet weak var webView:UIWebView!
    
    override func viewDidLoad() {
        let url = NSURL(fileURLWithPath: "privacy.html")
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
}

The html file is located in the root folder of my project but is inside a group. The webview is blank for me. Any ideas whats wrong? I am on xcode 6.1 and running this example on my iphone 6.

Ios Solutions


Solution 1 - Ios

To retrieve URLs for application resources, you should use URLForResource method of NSBundle class.

Swift 2

let url = NSBundle.mainBundle().URLForResource("privacy", withExtension:"html") 

Swift 3

let url = Bundle.main.url(forResource: "privacy", withExtension: "html")

Solution 2 - Ios

Swift 3: type safe

@IBOutlet weak var webView: UIWebView!
    
override func viewDidLoad() {
    super.viewDidLoad()
        
    // Adding webView content
    do {
        guard let filePath = Bundle.main.path(forResource: "myFile", ofType: "html")
            else {
                // File Error
                print ("File reading error")
                return
        }
            
        let contents =  try String(contentsOfFile: filePath, encoding: .utf8)
        let baseUrl = URL(fileURLWithPath: filePath)
        webView.loadHTMLString(contents as String, baseURL: baseUrl)
    }
    catch {
        print ("File HTML error")
    }
}

Keep in mind: NS = Not Swift :]

Solution 3 - Ios

// Point UIWebView
@IBOutlet weak var webView: UIWebView!
 
override func viewDidLoad() {
    super.viewDidLoad()
     
    //load a file
    var testHTML = NSBundle.mainBundle().pathForResource("privacy", ofType: "html")
    var contents = NSString(contentsOfFile: testHTML!, encoding: NSUTF8StringEncoding, error: nil)
    var baseUrl = NSURL(fileURLWithPath: testHTML!) //for load css file
     
    webView.loadHTMLString(contents, baseURL: baseUrl)
     
}

Solution 4 - Ios

Swift 3 with 3 lines :)

if let url = Bundle.main.url(forResource: "privacy", withExtension: "html") {
    webview.loadRequest(URLRequest(url: url))
}

Solution 5 - Ios

Swift version 2.1

this case also include Encoding

// load HTML String with Encoding
let path = NSBundle.mainBundle().pathForResource("policy", ofType: "html")
do {
    let fileHtml = try NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
    webView.loadHTMLString(fileHtml as String, baseURL: nil)
}
catch {
        
}

Solution 6 - Ios

Add the local HTML file into your project and name that file as home.html, then create the NSURLRequest using NSURL object. After that passing the request to web view it will load the requested URL into web view and if you are not using storyboard add the uiwebview into view controller view like the below code. 

 override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let localfilePath = NSBundle.mainBundle().URLForResource("home", withExtension: "html");
        let myRequest = NSURLRequest(URL: localfilePath!);
        myWebView.loadRequest(myRequest);
        self.view.addSubview(myWebView)
    }

For more reference please refer this http://sourcefreeze.com/uiwebview-example-using-swift-in-ios/

Solution 7 - Ios

This is worked for me:

@IBOutlet weak var mWebView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    
    mWebView.loadRequest(NSURLRequest(URL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("fineName", ofType: "html")!)))
    
}

Added App Transport Security Settings with Dictionary type in info.plist file. Also added sub key Allow Arbitrary Loads for App Transport Security Settings with type Boolean and value YES.

Here is tutorial.

EDITED

For Swift 3 (Xcode 8)

mWebView.loadRequest(URLRequest(url: URL(fileURLWithPath: Bundle.main.path(forResource: "test/index", ofType: "html")!)))

Solution 8 - Ios

You can load html string or local html file in UIWebView.

HTML string:

func loadHtmlCode() {
    let htmlCode = "<html><head><title>Wonderful web</title></head> <body><p>wonderful web. loading html code in <strong>UIWebView</strong></></body>"
    webView.loadHTMLString(htmlCode, baseURL: nil)
}

HTML file:

func loadHtmlFile() {
    let url = NSBundle.mainBundle().URLForResource("contactus", withExtension:"html")
    let request = NSURLRequest(URL: url!)
    webView.loadRequest(request)
}

Details can be found here: http://webindream.com/load-html-uiwebview-using-swift/

Solution 9 - Ios

Here is succinct version for Swift 4

  1. Add import import WebKit

  2. Add WebKit.framework in your project

enter image description here

@IBOutlet weak var webView: WKWebView!

if let filePath = Bundle.main.url(forResource: "FILE_NAME", withExtension: "html") {
  let request = NSURLRequest(url: filePath)
  webView.load(request as URLRequest)
}

Solution 10 - Ios

For swift 3 Use this:

do
    {
        let testHTML = Bundle.main.path(forResource: "about", ofType: "html")
        let contents =  try NSString(contentsOfFile: testHTML!, encoding: String.Encoding.utf8.rawValue)
        let baseUrl = NSURL(fileURLWithPath: testHTML!) //for load css file
    
        mWebView.loadHTMLString(contents as String, baseURL: baseUrl as URL)
    }
    catch
    {

    }

Solution 11 - Ios

Swift 4.2, Xcode 10.1, WKWebView load HTML from file. UIWebView is deprecated.

> In apps that run in iOS 8 and later, use the WKWebView class instead of using UIWebView.

import WebKit

@IBOutlet weak var webView: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    let localFilePath = Bundle.main.url(forResource: "document_terms_of_use", withExtension: "html")
    let request = NSURLRequest(url: localFilePath!)
    webView.load(request as URLRequest)
}

Solution 12 - Ios

swift 4.2 & 5:

let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 1024, height: 768))
let url = URL(string: PERS_Path)
webView?.navigationDelegate = self
webView?.uiDelegate = self
webView!.loadFileURL(url!, allowingReadAccessTo: url!)
self.view. addSubview(webView)

don't forget to add this WKNavigationDelegate, WKUIDelegate

Solution 13 - Ios

This worked for me (Xcode 8, Swift 3)

@IBOutlet weak var webViewer: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    
    let localfilePath = Bundle.main.url(forResource: "homeInfo", withExtension: "html");
    let myRequest = NSURLRequest(url: localfilePath!);
    webViewer.loadRequest(myRequest as URLRequest);
    self.view.addSubview(webViewer)
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUpCatView Question on Stackoverflow
Solution 1 - IosrintaroView Answer on Stackoverflow
Solution 2 - IosSébastien REMYView Answer on Stackoverflow
Solution 3 - IosJupiter ClsView Answer on Stackoverflow
Solution 4 - IosMBHView Answer on Stackoverflow
Solution 5 - IosSruit A.SukView Answer on Stackoverflow
Solution 6 - IosBharathi DevarasuView Answer on Stackoverflow
Solution 7 - IosAbduhafizView Answer on Stackoverflow
Solution 8 - Iosfarhad rubelView Answer on Stackoverflow
Solution 9 - IosAamirView Answer on Stackoverflow
Solution 10 - IosxevserView Answer on Stackoverflow
Solution 11 - IosnorbDEVView Answer on Stackoverflow
Solution 12 - IosZouhair SassiView Answer on Stackoverflow
Solution 13 - IosDieselView Answer on Stackoverflow