Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loadHTMLString baseURL:nil not working in iOS5

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] ;
like image 299
moon Avatar asked Nov 02 '11 13:11

moon


2 Answers

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.

like image 166
Oliver Avatar answered Oct 18 '22 19:10

Oliver


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.

like image 31
Yuyutsu Avatar answered Oct 18 '22 18:10

Yuyutsu