Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open local html file on Safari?

I want to open a local html file on Safari integration on my Swift 3 application.

I know how to do this with an url. This is the code that I use to do that:

let encodedString = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

let svc = SFSafariViewController(url: NSURL(string: encodedString!) as! URL)
self.present(svc, animated: true, completion: nil)

But I am not able to do the same with a local file. I have copied my html file on my project and I can see it on the directories tree but I am not able to make it to work. I have looked at Load local html into UIWebView using swift for reference.

How can I load a local html file into Safari integration?

Thanks in advance!

like image 585
Francisco Romero Avatar asked Jan 03 '17 17:01

Francisco Romero


1 Answers

You can't do it using SFSafariViewController

From Apple Documentation:

1. Choosing the Best Web Viewing Class

If your app lets users view websites from anywhere on the Internet, use the SFSafariViewController class. If your app customizes, interacts with, or controls the display of web content, use the WKWebView class.

2. if you look at declaration of init

convenience init(url URL: URL)

url: The URL to navigate to. The URL must use the http or https scheme.

Using Webkit or WebView

helloAshok.html

<html>
    <head>
    </head>
    <body>
        <br />
        <h2> Welcome ASHOK</h2>
    </body>
</html>

ViewContrller.swift

class ViewController: UIViewController {
    @IBOutlet weak var myWebView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let localFilePath = Bundle.main.url(forResource: "helloAshok", withExtension: "html")
        let request = URLRequest(url: localFilePath!)
        myWebView.loadRequest(request)
    }
}

Output:

enter image description here

like image 80
Ashok R Avatar answered Oct 20 '22 18:10

Ashok R