7

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] ;

2 Answers 2

23

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, I don't want to read local html file. I want to use directly like this. NSString* one = @"<html><head><title></title></head><body><img src=\"image.jpg\"/></body></html>";
@moon : yes, sorry, just replace htmlContent with your HTML. That was was I did when writing this code. I edit my answer.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.