2011-11-02 15 views
6

Tengo un problema con UIWebView. Quiero renderizar mi propio código html en UIWebView.loadHTMLString baseURL: nil no funciona en iOS5

si uso el siguiente código, está funcionando bien.

NSBundle *thisBundle = [NSBundle mainBundle]; 
    NSString *path = [thisBundle pathForResource:@"foo" ofType:@"html"]; 
    NSURL *baseURL = [NSURL fileURLWithPath:path]; 
    [self.webView loadHTMLString:@"foo.html" baseURL:baseURL]; 

Quiero presentar el html con el siguiente código. Pero no está funcionando. foo.html contiene exactamente el mismo contenido con NSString *. ¿Algún consejo? Gracias por adelantado. =)

NSString* one = @"<html><head><title></title></head><body><img src=\"image.jpg\"/></body></html>"; 
    [self.webView loadHTMLString:one baseURL:nil] ; 

Respuesta

23

utilizo este código que funciona a la perfección:

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 seguro de que imagen.jpg se incluye en su proyecto.

+0

Hola, no quiero leer el archivo html local. Quiero usar directamente así. * NSString uno = @ ""; – moon

+0

@moon: sí, lo siento, simplemente reemplace htmlContent con su HTML. Eso fue lo que hice al escribir este código. Edito mi respuesta. – Oliver

+0

Hola Oliver, sí, está funcionando. Muchas gracias. :) – moon

1

crear el archivo JS demo.js y agregar código

var hello = function(str){       return str; };

añadir UIWebView => Para insertar JavaScript en un archivo html maniquí y cargar en el que UIWebView

[self.webView loadHTMLString:@"<script src=\"demo.js\"></script>"               baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]]];

Aquí está el código para hacer JS llamada

NString *[email protected]"hi JavaScript"; 
NSString *function = [[NSString alloc] initWithFormat: @"hello(%@)", str]; 
NSString *result = [webView stringByEvaluatingJavaScriptFromString:function]; 

Ahora, hay un consejo de seguridad importante para hacer que esto realmente funcione: el UIWebView realmente debe cargarse una vista. No tiene que ser visible, pero para que el motor WebKit ejecute el JS, debe estar en una vista.

Cuestiones relacionadas