Load local html into UIWebView using swift

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.


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")

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 :]


// 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)

}

Swift 3 with 3 lines :)

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