Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 670
UpCat Avatar asked Oct 30 '14 07:10

UpCat


People also ask

How do I import HTML into WKWebView?

How to load a HTML string into a WKWebView or UIWebView: loadHTMLString() If you want to load resources from a particular place, such as JavaScript and CSS files, you can set the baseURL parameter to any URL .

Which method is used to load the content into a UIWebView?

Use the loadHTMLString(_:baseURL:) method to begin loading local HTML files or the loadRequest(_:) method to begin loading web content. Use the stopLoading() method to stop loading, and the isLoading property to find out if a web view is in the process of loading.


1 Answers

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") 
like image 93
rintaro Avatar answered Oct 07 '22 10:10

rintaro