Correct way to load image into UIWebView from NSData object

╄→гoц情女王★ 提交于 2019-11-27 13:38:07

I tested the code with PNG ("image/png"), JPG ("image/jpeg") and GIF ("image/gif"), and it works as expected:

[webView loadData:imageData MIMEType:imageMIMEType textEncodingName:nil baseURL:nil];

Now, what's wrong with your app?

  • the imageData is not a well-formed image data. Try opening the file with a web browser or an image editor to check it.
  • the MIME type is incorrect. Look at the first bytes of the data to determine the actual file type.
  • webView is not connected in IB, is nil, is hidden, is covered with another view, is off screen, has a CGRectZero frame, etc.

I did not really try to load image to UIWebView but a google search gives me. I think your image string must have a good path and looks like a URL

NSString *imagePath = [[NSBundle mainBundle] resourcePath];
imagePath = [imagePath stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
imagePath = [imagePath stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

NSString *HTMLData = @"
<h1>Hello this is a test</h1>
<img src="sample.jpg" alt="" width="100" height="100" />";
[webView loadHTMLString:HTMLData baseURL:[NSURL URLWithString: [NSString stringWithFormat:@"file:/%@//",imagePath]]];

You can see more details here : Loading local files to UIWebView

pratap shaik
UIImage *screenshot= [UIImage imageAtPath:
                              [[NSBundle mainBundle] pathForResource:@"MfLogo_aboutus" ofType:@"png"]]; 
NSData *myData = UIImagePNGRepresentation(screenshot); 
[vc addAttachmentData:myData mimeType:@"image/png" fileName:@"logo.png"];

You can load urlImage into webview which is not saved locally as shown below code

NSString *str = @"";
        str = [str stringByAppendingString:@"http://t3.gstatic.com/images?q=tbn:7agzdcFyZ715EM:http://files.walerian.info/Funny/Animals/funny-pictures-firefox-file-transfer-is-complete.jpg"];
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
        [webView loadData:data MIMEType:@"application/jpg" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@"http://google.com"]];
Brian W

I had the same problem and I found somewhere else that you have to provide a value in the baseURL parameter. I also had encoding set:

textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@"http://localhost/"]];

When I had nil in the baseURL parameter it would not load. By putting something that's basically irrelevant in there the MS docs all worked.

You may want to try assigning a delegate to the webview and implementing the method:

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error

To see more specifically what error you're getting. If it doesn't get called, implement the method:

- (void)webViewDidFinishLoad:(UIWebView *)webView

as well, just to make sure something is happening, otherwise there might be an issue with UIWebView (assuming you haven't returned NO from webView:shouldStartLoadWithRequest:navigationType:)

To expand on Ed Marty's comment:

The HTML command to put in a base 64 image is:

<img src="data:image/png;base64,##PUT THE BASE64 DATA HERE###" />

I have a category (I'm not sure where it came from, not me...) available on my website that converts NSData to it's Base64 string representation.

Header Implementation

Easy enough to do, assuming 'imageData' is the NSData variable containing your image: [imageData base64Encoding] into the above string.

Chandaboy

try this code

// 1) Get: Get string from “outline.plist” in the “DrillDownSave”-codesample.
savedUrlString = [item objectForKey: @"itemUrl"];

// 2) Set: The url in string-format, excluding the html-appendix.
NSString *tempUrlString = savedUrlString;

// 3) Set: Format a url-string correctly. The html-file is located locally.
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:tempUrlString ofType:@”html”];

// 4) Set: Set an “NSData”-object of the url-sting.
NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];

// 5. Gets the path to the main bundle root folder
NSString *imagePath = [[NSBundle mainBundle] resourcePath];

// 6. Need to be double-slashes to work correctly with UIWebView, so change all “/” to “//”
imagePath = [imagePath stringByReplacingOccurrencesOfString:@"/" withString:@"//"];

// 7. Also need to replace all spaces with “%20″
imagePath = [imagePath stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

//  Load:   Loads the local html-page.
[webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:[NSString stringWithFormat:@"file:/%@//",imagePath]]];

Here's an alternative method:

Save the image you downloaded into your documents folder. Then get that image's url. Then write a simple html file using that image url in the IMG SRC tag.

NSLog(@"url=%@", fileURL); // fileURL is the image url in doc folder of your app


//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/toOpen.html",
                      documentsDirectory];

//create simple html file and format the url into the IMG SRC tag
NSString *content = [NSString stringWithFormat:@"<html><body><img src=%@></body></html>",fileURL];
//save content to the documents directory
[content writeToFile:fileName
          atomically:NO
            encoding:NSStringEncodingConversionAllowLossy
               error:nil]; // now we have a HTML file in our doc

// open the HTML file we wrote in the webview

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"life.html"];
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[yourWebView loadRequest:request];
NSString *pathForFile = [[NSBundle mainBundle] pathForResource: @"fireballscopy" ofType: @"gif"];
    NSData *dataOfGif = [NSData dataWithContentsOfFile: pathForFile];
    [Web_View loadData:dataOfGif MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!