Search code examples
iosswiftwebviewuiwebview

Swift 3 webView local HTML


I need to load local HTML, CSS and JS into an iOS app to make my boss happy. I'm using Xcode 8.3.1 and Swift 3. I have created a new project with a WebView placed in my Main.storyboard

Other StackOverflow resources helped me get this far:

@IBOutlet weak var webView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let urlpath = Bundle.main.path(forResource: "index", ofType: "html");
    let requesturl = URL(string: urlpath!)
    let request = URLRequest(url: requesturl!)
    webView.mainFrame.load(request)
}

I get this error:

Value of type 'UIWebView' has no member 'mainFrame'

When I remove mainFrame it says I'm missing a mimeType. Can anyone help? I'm obviously a noob to Swift.


Solution

  • mainFrame is from the class WebView which is only for macOS.

    Since you are using UIWebView, you need to use webView.loadRequest.

    You also have a problem with your URL. Either use URL(fileURLWithPath:) to create the URL from the path string or, better yet, use Bundle.main.url(forResource:withExtension:) and get the URL directly.

    You might also want to use WKWebView instead of UIWebView. It has a lot more features and it may be more useful for your needs.