How to load local html file into UIWebView How to load local html file into UIWebView ios ios

How to load local html file into 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? 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 - loadRequest exposes "a universal Cross-Site Scripting vulnerability." 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 <img src="some.png">, the webView will load some.png from your project.


by this you can load html file which is in your project Assets(bundle) to webView.

 UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];    [web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]                                 pathForResource:@"test" ofType:@"html"]isDirectory:NO]]];

may be this is useful to you.