loadHTMLString baseURL:nil not working in iOS5

喜你入骨 提交于 2019-12-30 06:45:08

问题


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

回答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.




回答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.



来源:https://stackoverflow.com/questions/7981083/loadhtmlstring-baseurlnil-not-working-in-ios5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!