How to load local html file into UIWebView

199,043

Solution 1

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.

Solution 2

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.

Solution 3

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.

Solution 4

I guess you need to allocate and init your webview first::

- (void)viewDidLoad
{
    NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html" inDirectory:@"html_files"];
    NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
    webView = [[UIWebView alloc] init];
    [webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]];

    [super viewDidLoad];
}

Solution 5

A Simple Copy-Paste code snippet:

-(void)LoadLocalHtmlFile:(NSString *)fileName onWebVu:(UIWebView*)webVu
{
    [webVu loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:fileName ofType:@"html"]isDirectory:NO]]];
}

Note:

Make sure the html file's Target membership is checked otherwise following exception will get thrown :-

enter image description here

Terminating app due to uncaught exception

'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:isDirectory:]: nil string parameter'

Share:
199,043

Related videos on Youtube

madcoderz
Author by

madcoderz

My name is Ernesto Delgado. I´m currently working as a freelance Java Developer. As of now, I live in Chile but my studies were based in Sweden. I have almost 10 years of experience in Java, Hibernate, SQL, Spring, Apache Tomcat, HTML, CSS, Maven, etc. My responsibilities include the design and development of well-structurated and scalable code with Java technologies, providing technical support and knowledge transfer to my co-workers. I have worked for big companies like ENEA, Svenska Lotteriet and TV4.

Updated on July 08, 2022

Comments

  • madcoderz
    madcoderz almost 2 years

    I'm trying to load a html file into my UIWebView but it won't work. Here's the stage: I have a folder called html_files in my project. Then I created a webView in interface builder and assigned an outlet to it in the viewController. This is the code I'm using to append the html file:

    -(void)viewDidLoad
    {
        NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html" inDirectory:@"html_files"];
        NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
        [webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]];
        [super viewDidLoad];
    }
    

    That won't work and the UIWebView is blank. I'd appreciate some help.

  • madcoderz
    madcoderz almost 13 years
    That didn't work, i did NSLog(@"%@",htmlFile); just to check and it says null.
  • madcoderz
    madcoderz almost 13 years
    that's the same i'm doing the only difference is that you're creating the webView programmatically. But thanks anyway
  • user478681
    user478681 almost 13 years
    So that mean resource not found. Check with just: NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html"]; without inDirectory
  • AJPatel
    AJPatel almost 13 years
    u get the path of that html file check by NSLog.
  • madcoderz
    madcoderz almost 13 years
    without inDirectory i got: iPhone Simulator/4.3.2/Applications/49351078-9423-4A24-8E58-B2A0599‌​61097/WebviewTest.ap‌​p/sample.html but the html didn't show up in the screen it was still empty. I'm i missing something else? Here's the sample project: http://www.box.net/shared/rb05b4ppjnbof1r33gh7
  • user478681
    user478681 almost 13 years
    try to scroll up/down. you will see your html :)
  • user478681
    user478681 almost 13 years
    you just need to fix frame of your webview
  • James
    James almost 11 years
    I couldn't get the accepted answer on this page to work -- but this approach worked first time. iOS has moved on since the original answer, I think. Thanks.
  • Durai Amuthan.H
    Durai Amuthan.H over 10 years
    Target membership of html file should be checked otherwise the following exception will get thrown :-Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:isDirectory:]: nil string parameter'
  • Amy
    Amy about 10 years
    Thanks for this answer. What's different about this vs. the accepted answer is links in the HTML doc work.
  • paulmelnikow
    paulmelnikow about 10 years
    This answer has a lot of votes but seems to be out of date. Local image and CSS assets would not load using this approach. See this answer instead.
  • Rushi trivedi
    Rushi trivedi over 9 years
    @user478681 In YOur Answer Code shows NSString* htmlString=nil; can you help whats the problem ?
  • ingconti
    ingconti over 8 years
    better to use let to test against error in path/no file:
  • ED-209
    ED-209 almost 8 years
    According to Apple To help you avoid being vulnerable to security attacks, be sure to use loadHTMLString:baseURL: to load local HTML files; don’t use loadRequest:.
  • Mihir Oza
    Mihir Oza almost 8 years
    Accepted answer is not working for me. Thanks @neal Ehardt this answer is working for me.
  • Renan Franca
    Renan Franca about 7 years
    This only work for me if the html file isn't inside any folder
  • Pierre F
    Pierre F over 4 years
    This won't load linked files such as <img src="..." />