sirve que para example app iphone html uikit uiwebview

iphone - que - Uso de HTML e imágenes locales dentro de UIWebView



wkwebview (13)

Después de leer un par de capítulos en iOS 6 Programming Cookbok y comenzar a aprender la programación de Object-c e iOS, me gustaría agregar que si uno va a cargar recursos de un paquete personalizado y usarlo en una vista web , se puede lograr así:

NSString *resourcesBundlePath = [[NSBundle mainBundle] pathForResource:@"Resources" ofType:@"bundle"]; NSBundle *resourcesBundle = [NSBundle bundleWithPath:resourcesBundlePath]; [self.outletWebView loadHTMLString:[html description] baseURL:[resourcesBundle bundleURL]];

Luego, en su html puede referirse a un recurso usando el paquete "personalizado" como su ruta base:

body { background-image:url(''img/myBg.png''); }

Tengo una UIWebView en mi aplicación que quiero usar para mostrar una imagen que se vinculará a otra url.

Estoy usando

<img src="image.jpg" /> to load the image.

El problema es que la imagen no se carga (es decir, no se puede encontrar) aunque se haya agregado como recurso en mi proyecto y se haya copiado en el paquete.

Intenté usar NSBundle para obtener la ruta completa de la imagen y usarla, y aún no aparece en la vista web.

¿Algunas ideas?


En Swift 3:

webView.loadHTMLString("<img src=/"myImg.jpg/">", baseURL: Bundle.main.bundleURL)

Esto funcionó para mí incluso cuando la imagen estaba dentro de una carpeta sin modificaciones.


Estas respuestas me ayudaron, específicamente el archivo: // xxxxxxx.xxx, pero tuve que hacer una solución para mostrar la imagen.

En mi caso, tengo un archivo HTML en mi servidor que descargo al directorio de documentos. Quiero que se muestre con un gráfico local en un UIWebView que no pude ponerme a trabajar. Esto es lo que hice:

  1. Copie el archivo de NSBundle en el directorio de documentos locales
  2. Haga referencia al archivo en mi documento HTML como "file: // filename.png"

Por lo tanto, en el inicio, copie el archivo al directorio de documentos:

-(BOOL)copyBundleFilesToDocumentsDirectoryForFileName:(NSString *)fileNameToCopy OverwriteExisting:(BOOL)overwrite { //GET DOCUMENTS DIR //Search for standard documents using NSSearchPathForDirectoriesInDomains //First Param = Searching the documents directory //Second Param = Searching the Users directory and not the System //Expand any tildes and identify home directories. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [paths objectAtIndex:0]; //COPY FILE FROM NSBUNDLE File to Local Documents Dir NSString *writableFilePath = [documentsDir stringByAppendingPathComponent:fileNameToCopy]; NSFileManager *fileManager = [NSFileManager defaultManager]; NSError *fileError; DDLogVerbose(@"File Copy From Bundle to Documents Dir would go to this path: %@", writableFilePath); if ([fileManager fileExistsAtPath:writableFilePath]) { DDLogVerbose(@"File %@ already exists in Documents Dir", fileNameToCopy); if (overwrite) { [fileManager removeItemAtPath:writableFilePath error:nil]; DDLogVerbose(@"OLD File %@ was Deleted from Documents Dir Successfully", fileNameToCopy); } else { return (NO); } } NSArray *fileNameParts = [fileNameToCopy componentsSeparatedByString:@"."]; NSString *bundlePath = [[NSBundle mainBundle]pathForResource:[fileNameParts objectAtIndex:0] ofType:[fileNameParts objectAtIndex:1]]; BOOL success = [fileManager copyItemAtPath:bundlePath toPath:writableFilePath error:&fileError]; if (success) { DDLogVerbose(@"Copied %@ from Bundle to Documents Dir Successfully", fileNameToCopy); } else { DDLogError(@"File %@ could NOT be copied from bundle to Documents Dir due to error %@!!", fileNameToCopy, fileError); } return (success); }


Me encontré con este problema también. En mi caso, estaba lidiando con algunas imágenes que no estaban localizadas y otras que sí, en varios idiomas. Una URL base no obtuvo las imágenes dentro de las carpetas localizadas para mí. Lo resolví haciendo lo siguiente:

// make sure you have the image name and extension (for demo purposes, I''m using "myImage" and "png" for the file "myImage.png", which may or may not be localized) NSString *imageFileName = @"myImage"; NSString *imageFileExtension = @"png"; // load the path of the image in the main bundle (this gets the full local path to the image you need, including if it is localized and if you have a @2x version) NSString *imagePath = [[NSBundle mainBundle] pathForResource:imageFileName ofType:imageFileExtension]; // generate the html tag for the image (don''t forget to use file:// for local paths) NSString *imgHTMLTag = [NSString stringWithFormat:@"<img src=/"file://%@/" />", imagePath];

Luego, use imgHTMLTag en su código HTML de UIWebView cuando cargue los contenidos.

Espero que esto ayude a cualquiera que se encuentre con el mismo problema.


Mi solución compleja (o tutorial) para rss-feed (get in RSSItems) funciona solo en el dispositivo:

#define CACHE_DIR [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] for (RSSItem *item in _dataSource) { url = [NSURL URLWithString:[item link]]; request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"GET"]; [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { @autoreleasepool { if (!error) { NSString *html = [[NSString alloc] initWithData:data encoding:NSWindowsCP1251StringEncoding]; { NSError *error = nil; HTMLParser *parser = [[HTMLParser alloc] initWithString:html error:&error]; if (error) { NSLog(@"Error: %@", error); return; } HTMLNode *bodyNode = [parser body]; NSArray *spanNodes = [bodyNode findChildTags:@"div"]; for (HTMLNode *spanNode in spanNodes) { if ([[spanNode getAttributeNamed:@"class"] isEqualToString:@"page"]) { NSString *absStr = [[response URL] absoluteString]; for (RSSItem *anItem in _dataSource) if ([absStr isEqualToString:[anItem link]]){ NSArray *spanNodes = [bodyNode findChildTags:@"img"]; for (HTMLNode *spanNode in spanNodes){ NSString *imgUrl = [spanNode getAttributeNamed:@"src"]; if (imgUrl){ [anItem setImage:imgUrl]; break; } } [anItem setHtml:[spanNode rawContents]]; [self subProcessRSSItem:anItem]; } } } [parser release]; } if (error) { NSLog(@"Error: %@", error); return; } [[NSNotificationCenter defaultCenter] postNotificationName:notification_updateDatasource object:self userInfo:nil]; }else NSLog(@"Error",[error userInfo]); } }];

y

- (void)subProcessRSSItem:(RSSItem*)item{ NSString *html = [item html]; if (html) { html = [html stringByReplacingOccurrencesOfString:@"<div class=/"clear/"></div>" withString:@""]; html = [html stringByReplacingOccurrencesOfString:@"<p class=/"link/">" withString:@""]; html = [html stringByReplacingOccurrencesOfString:@"<div class=/"page/">" withString:@""]; html = [html stringByReplacingOccurrencesOfString:@"</div>" withString:@""]; NSArray *array1 = [html componentsSeparatedByString:@"<a"]; if ([array1 count]==2) { NSArray *array2 = [html componentsSeparatedByString:@"a>"]; html = [[array1 objectAtIndex:0] stringByAppendingString:[array2 objectAtIndex:1]]; } NSURL *url; NSString *fileName; NSString *filePath; BOOL success; if ([item image]) { url = [NSURL URLWithString: [hostString stringByAppendingString:[item image]]]; NSData *imageData = [NSData dataWithContentsOfURL:url]; fileName = [[[url relativePath] componentsSeparatedByString:@"/"] lastObject]; filePath = [NSString stringWithFormat:@"%@/%@", CACHE_DIR, fileName]; //save image locally success = [[NSFileManager defaultManager] createFileAtPath:filePath contents:imageData attributes:nil]; //replace links html = [html stringByReplacingOccurrencesOfString:[item image] withString:filePath]; [item setImage:fileName]; //Передадим обновление интерфейса, снабдив индексом обновляемой ячейки [[NSNotificationCenter defaultCenter] postNotificationName:notification_updateRow object:self userInfo:[NSDictionary dictionaryWithObject:@([_dataSource indexOfObject:item]) forKey:@"row"]]; } //finalize html html = [NSString stringWithFormat:@"<html><body>%@</body></html>",html]; fileName = [[[item link] componentsSeparatedByString:@"/"] lastObject]; filePath = [NSString stringWithFormat:@"%@/%@", CACHE_DIR, fileName]; success = [[NSFileManager defaultManager] createFileAtPath:filePath contents:[html dataUsingEncoding:NSUTF8StringEncoding] attributes:nil]; [item setHtml: (success)?filePath:nil];//for direct download in other case }

}

en el controlador View

- (void)viewDidAppear:(BOOL)animated{ RSSItem *item = [[DataSingleton sharedSingleton] selectedRSSItem]; NSString* htmlString = [NSString stringWithContentsOfFile:[item html] encoding:NSUTF8StringEncoding error:nil]; NSURL *baseURL = [NSURL URLWithString:CACHE_DIR]; [_webView loadHTMLString:htmlString baseURL:baseURL];

}

clase de elemento de rss

#import <Foundation/Foundation.h> @interface RSSItem : NSObject @property(nonatomic,retain) NSString *title; @property(nonatomic,retain) NSString *link; @property(nonatomic,retain) NSString *guid; @property(nonatomic,retain) NSString *category; @property(nonatomic,retain) NSString *description; @property(nonatomic,retain) NSString *pubDate; @property(nonatomic,retain) NSString *html; @property(nonatomic,retain) NSString *image; @end

parte de cualquier html con imagen

<html><body> <h2>blah-blahTC One Tab 7</h2> <p>blah-blah НТС One.</p> <p><img width="600" height="412" alt="" src="/Users/wins/Library/Application Support/iPhone Simulator/5.0/Applications/2EAD8889-6482-48D4-80A7-9CCFD567123B/Library/Caches/htc-one-tab-7-concept-1(1).jpg"><br><br> blah-blah (Hasan Kaymak) blah-blah HTC One Tab 7, blah-blah HTC One. <br><br> blah-blah microSD.<br><br> blah-blah Wi-Fi to 4G LTE.</p> </p> </body></html>

imagen guardada para el nombre htc-one-tab-7-concept-1 (1) .jpg


Puede agregar una carpeta (digamos WEB con las subcarpetas css, img y js y file test.html) a su proyecto seleccionando Agregar archivos a "MyProj" y seleccionando Crear referencias de carpeta . Ahora el siguiente código se ocupará de todas las imágenes referidas, css y javascript

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"WEB/test.html" ofType:nil]; [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];


Si utiliza enlaces relativos a imágenes, entonces las imágenes no se mostrarán ya que no se conservarán todas las estructuras de carpetas después de compilar la aplicación de iOS. Lo que puede hacer es convertir su carpeta web local en un paquete agregando la extensión de nombre de archivo " .bundle ".

Por lo tanto, si su sitio web local está en una carpeta " www ", debe cambiar el nombre a " www.bundle ". Esto permite conservar las carpetas de imágenes y la estructura del directorio. A continuación, cargue el archivo '' index.html '' en WebView como una cadena HTML con '' baseURL '' (configurado en www.bundle path) para permitir la carga de enlaces de imágenes relativos.

NSString *mainBundlePath = [[NSBundle mainBundle] resourcePath]; NSString *wwwBundlePath = [mainBundlePath stringByAppendingPathComponent:@"www.bundle"]; NSBundle *wwwBundle = [NSBundle bundleWithPath:wwwBundlePath]; if (wwwBundle != nil) { NSURL *baseURL = [NSURL fileURLWithPath:[wwwBundle bundlePath]]; NSError *error = nil; NSString *page = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil]; NSString *pageSource = [NSString stringWithContentsOfFile:page encoding:NSUTF8StringEncoding error:&error]; [self.webView loadHTMLString:pageSource baseURL:baseURL]; }


Tuve un problema similar, pero todas las sugerencias no ayudaron.

Sin embargo, el problema era el * .png en sí mismo. No tenía canal alfa De alguna manera, Xcode ignora todos los archivos png sin canal alfa durante el proceso de implementación.


Usar rutas o archivos relativos: las rutas para hacer referencia a imágenes no funcionan con UIWebView. En su lugar, debe cargar el código HTML en la vista con el URLUR base correcto:

NSString *path = [[NSBundle mainBundle] bundlePath]; NSURL *baseURL = [NSURL fileURLWithPath:path]; [webView loadHTMLString:htmlString baseURL:baseURL];

A continuación, puede referirse a sus imágenes de esta manera:

<img src="myimage.png">

(de uiwebview revisited )


Utilizar esta:

[webView loadHTMLString:htmlString baseURL:[[NSBundle mainBundle] bundleURL]];


Versión rápida de Adam Alexander respuesta del Objetivo C:

let logoImageURL = NSURL(fileURLWithPath: "/(Bundle.main.bundlePath)/PDF_HeaderImage.png")


intente utilizar cadena de imagen base64.

NSData* data = UIImageJPEGRepresentation(image, 1.0f); NSString *strEncoded = [data base64Encoding]; <img src=''data:image/png;base64,%@ ''/>,strEncoded


Versión Swift de la respuesta de Lithu TV:

webView.loadHTMLString(htmlString, baseURL: NSBundle.mainBundle().bundleURL)