Swift – Load Local File or URL in NSWebView OSX, Not UIWebView

i0S Swift Issue

Question or problem in the Swift programming language:

Ok, so been working on this issue for a while now, trying to load a local HTML file or URL to a web view in Swift for OS X not iOS.

@IBOutlet weak var Webview: WebView!

func applicationDidFinishLaunching(aNotification: NSNotification?) {
    // Insert code here to initialize your application

    var url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("pageName", ofType: "html"))

    //var url = NSURL(string: "http://www.google.com")

    var request = NSURLRequest(URL: url)



So I know the above works with iOS and UIKit but it does not work in OS X it gives the error Webview does not have a member named loadRequest and it does not seem to have any methods for loading a URL any help is appreciated!

How to solve the problem:

Solution 1:

You must revise your code this way to request the URL as a string first. This works perfectly in swift without caching assets etc:

@IBOutlet var webView: UIWebView!

var urlpath = NSBundle.mainBundle().pathForResource("index", ofType: "html");

func loadAddressURL(){
    let requesturl = NSURL(string: urlpath!)
    let request = NSURLRequest(URL: requesturl)

override func viewDidLoad() {

    loadAddressURL() //func above

    // Do any additional setup after loading the view, typically from a nib.

Solution 2:

Use Webview.mainFrame.loadRequest(request) instead of Webview.loadRequest(request)

Solution 3:

You have to use it:

        objweb.delegate = self
        var path = NSBundle.mainBundle().bundlePath

        var baseUrl  = NSURL.fileURLWithPath("\(path)")

        let bundle = NSBundle.mainBundle()
        let pathhtml = bundle.pathForResource("pageName", ofType: "html")
        let content = NSString.stringWithContentsOfFile(pathhtml) as String

        objweb.loadHTMLString(content, baseURL: baseUrl)

Hope this helps!