que app iphone uiwebview nsdata

iphone - app - Manera correcta de cargar la imagen en UIWebView desde el objeto NSData



wkwebview ios (10)

He descargado una imagen gif en un objeto NSData (he comprobado el contenido del objeto NSData y definitivamente se ha completado). Ahora quiero cargar esa imagen en mi UIWebView. He intentado lo siguiente:

[webView loadData:imageData MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];

pero me sale un UIWebView en blanco. Cargar la imagen desde la misma URL directamente funciona bien:

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageUrl]]; [imageView loadRequest:request];

¿Necesito establecer el textEncodingName en algo, o estoy haciendo algo incorrecto?

Quiero cargar la imagen manualmente para poder informar el progreso al usuario, pero es un gif animado, así que cuando esté listo quiero mostrarlo en un UIWebView.

Edición: ¿Quizás necesito envolver mi imagen en HTML de alguna manera? ¿Hay una manera de hacer esto sin tener que guardarlo en el disco?


Aquí hay un método alternativo:

Guarda la imagen que descargaste en tu carpeta de documentos. Entonces consigue la url de esa imagen. Luego, escriba un archivo html simple utilizando esa url de imagen en la etiqueta IMG SRC.

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


Para ampliar el comentario de Ed Marty:

El comando HTML para poner en una imagen base 64 es:

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

Tengo una categoría (no estoy segura de dónde vino, no yo ...) disponible en mi sitio web que convierte NSData a su representación de cadena Base64.

Header Header

Lo suficientemente fácil de hacer, asumiendo que ''imageData'' es la variable NSData que contiene su imagen: [imageData base64Encoding] en la cadena anterior.


Probé el código con PNG ("imagen / png"), JPG ("imagen / jpeg") y GIF ("imagen / gif"), y funciona como se esperaba:

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

Ahora, ¿qué pasa con tu aplicación?

  • imageData no es un dato de imagen bien formado. Intente abrir el archivo con un navegador web o un editor de imágenes para comprobarlo.
  • el tipo MIME es incorrecto Mire los primeros bytes de los datos para determinar el tipo de archivo real.
  • webView no está conectado en IB, es nulo, está oculto, está cubierto con otra vista, está fuera de pantalla, tiene un marco CGRectZero, etc.

Puede cargar urlImage en webview que no se guarda localmente como se muestra debajo del código

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


Puede intentar asignar un delegado a la vista web e implementar el método:

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

Para ver más específicamente qué error estás recibiendo. Si no se llama, implementa el método:

- (void)webViewDidFinishLoad:(UIWebView *)webView

también, solo para asegurarse de que algo está sucediendo, de lo contrario podría haber un problema con UIWebView (asumiendo que no ha devuelto NO desde webView:shouldStartLoadWithRequest:navigationType:


Realmente no intenté cargar la imagen en UIWebView, pero una búsqueda en Google me da. Creo que la cadena de su imagen debe tener un buen camino y se parece a una 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]]];

Puede ver más detalles aquí: Cargar archivos locales en UIWebView


Tuve el mismo problema y encontré en otro lugar que tiene que proporcionar un valor en el parámetro baseUR L. También tuve el conjunto de codificación:

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

Cuando tuve nil en el parámetro baseURL no se cargaría. Al poner algo que es básicamente irrelevante allí, todos los documentos de MS funcionaron.


prueba este código

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


NSString *pathForFile = [[NSBundle mainBundle] pathForResource: @"fireballscopy" ofType: @"gif"]; NSData *dataOfGif = [NSData dataWithContentsOfFile: pathForFile]; [Web_View loadData:dataOfGif MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];


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