loadHTMLString baseURL:nil not working in iOS5

18,617

Solution 1

I use this code that works perfectly :

NSString* htmlContent = @"<html><head><title></title></head><body><img src='image.jpg' /></body></html>";
[self.webView loadHTMLString:htmlContent baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];

Bu sure that image.jpg is included into your project.

Solution 2

create JS file demo.js and add code

var hello = function(str){       return str; };

add UIWebView => To embed JavaScript in a dummy html file and load that into the UIWebView

[self.webView loadHTMLString:@"<script src=\"demo.js\"></script>"               baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]]];

Here is the code to make JS call

NString *str=@"hi JavaScript";
NSString *function = [[NSString alloc] initWithFormat: @"hello(%@)", str];
NSString *result = [webView stringByEvaluatingJavaScriptFromString:function];

Now, there is one important safety tip to make this actually work: The UIWebView must actually be loaded a view. It doesn’t have to be visible, but in order for the WebKit engine to execute the JS, it must be on a view.

Share:
18,617
moon
Author by

moon

Updated on June 16, 2022

Comments

  • moon
    moon almost 2 years

    I got a problem with UIWebView. I want to render my own html code in UIWebView.

    if I use the below code, it's working fine.

        NSBundle *thisBundle = [NSBundle mainBundle];
        NSString *path = [thisBundle pathForResource:@"foo" ofType:@"html"];
        NSURL *baseURL = [NSURL fileURLWithPath:path];
        [self.webView loadHTMLString:@"foo.html" baseURL:baseURL];
    

    I want to render the html with below code. But it's not working. foo.html contains exactly the same content with the NSString* one. Any hints? Thanks in advance. =)

        NSString* one = @"<html><head><title></title></head><body><img src=\"image.jpg\"/></body></html>";
        [self.webView loadHTMLString:one baseURL:nil] ;