Uiwebview Local Html Javascript File
Hello All, Just as a learning exercise I took a webpage that I have, which runs some javascript functions, and am trying to bring it into an UIWebView.
Probably it is better to use NSString and load html document as follows: Objective-C NSString.htmlFile = NSBundle mainBundle pathForResource:@'sample' ofType:@'html'; NSString. htmlString = NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil; webView loadHTMLString:htmlString baseURL: NSBundle mainBundle bundleURL; Swift let htmlFile = NSBundle.mainBundle.pathForResource('fileName', ofType: 'html') let html = try? String(contentsOfFile: htmlFile!, encoding: NSUTF8StringEncoding) webView.loadHTMLString(html!, baseURL: nil) Swift 3 has few changes: let htmlFile = Bundle.main.path(forResource: 'intro', ofType: 'html') let html = try?
Javascript File Download
String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8) webView.loadHTMLString(html!, baseURL: nil) Did you try? Also check that the resource was found by pathForResource:ofType:inDirectory call. EDIT 2016-05-27 - Make sure you own every single asset that you load. If you load a bad script, it can load anything it wants. If you need relative links to work locally, use this: NSURL.url = NSBundle mainBundle URLForResource:@'my' withExtension:@'html'; webView loadRequest:NSURLRequest requestWithURL:url; The bundle will search all subdirectories of the project to find my.html.
(the directory structure gets flattened at build time) If my.html has the tag, the webView will load some.png from your project. Here the way the working of HTML file with Jquery. webview=UIWebView allocinitWithFrame:CGRectMake(0, 0, 320, 568); self.view addSubview:webview; NSString.filePath=NSBundle mainBundlepathForResource:@'jquery' ofType:@'html' inDirectory:nil; NSLog(@'%@',filePath); NSString.htmlstring=NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil; webview loadRequest:NSURLRequest requestWithURL:NSURL fileURLWithPath:filePath; or webview loadHTMLString:htmlstring baseURL:nil; You can use either the requests to call the HTML file in your UIWebview. A new way to do this using swift. The UIWebView is no more and WKWebView is the new class to load web pages, which ensures the Safari features to the web view. Import WebKit let preferences = WKPreferences preferences.javaScriptCanOpenWindowsAutomatically = false let configuration = WKWebViewConfiguration configuration.preferences = preferences let webView = WKWebView(frame: self.view.bounds, configuration: configuration) let request = NSURLRequest(URL: NSURL(string: 'webView.loadRequest(request).