9

I have a UIWebView and I want to load an SVG image into it. The contents of the file is pure SVG i.e. <svg>...</svg>. The file loads fine into normal and Mobile Safari, and also in a UIWebView using loadRequest: by doing the following:

url = [NSURL fileURLWithPath:path];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[webView loadRequest:req];

However, if I load the contents of the file into a string, and try to load the HTML string into the webview, nothing displays:

html = [NSString stringWithContentsOfFile:path
                                encoding:NSASCIIStringEncoding
                                   error:nil];
[webView loadHTMLString:html baseURL:nil];

Is there any reason between the above two techniques? Should they not give the same results? The file is pure ASCII, so I don't think there is an encoding issue.

I guess I can get what I need done right now by using a file, but I hate to use the filesystem for non persistent data.

Any help is greatly appreciated!!!

Thanks, Ron

Ron
  • 1,305
  • 2
  • 14
  • 22
  • Could the problem be that my "html" is not really html? My file begins and ends with ' ... '. Is it possible that loading a request handles non-HTML files, while loadHTMLString requires the text to be HTML? – Ron Apr 12 '11 at 19:36

2 Answers2

9

To solve this issue you have to use loadData:MIMEType:textEncodingName:baseURL: instead.

NSData *data = [html dataUsingEncoding:NSUTF8StringEncoding];
[webView loadData:data MIMEType:@"application/xhtml+xml" textEncodingName:@"utf-8" baseURL:baseUrl];
Styx
  • 9,863
  • 8
  • 43
  • 53
  • I used MIMEType "text/html" since xhtml+xml is strict and will cause rendering errors if the html isn't perfect (i.e. all tags must be closed properly, etc) – Larry Aug 08 '13 at 06:08
0

I am not sure about this but if the baseURL is set to nil, I think the webview does not know from where to load the contents.

Hope this SO question helps u Link to resources inside WebView - iPhone

Community
  • 1
  • 1
visakh7
  • 26,380
  • 8
  • 55
  • 69
  • Thanks for the information! In my case, however, I don't think that is what is causing the problem since the HTML is completely self contained. – Ron Apr 12 '11 at 19:34