Cargar recursos desde la ruta relativa usando html local en uiwebview


Tengo una aplicación iOS muy simple con un uiwebview cargando una página de prueba muy simple (prueba.html):

<html>
<body>
<img src="img/myimage.png" />
</body>
</html>

Cargo esta prueba.archivo html en mi vista web:

NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"];
NSString *html = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSURL *baseUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
[webView loadHTMLString:html baseURL:baseUrl];

Esto funciona bien si hago referencia a la imagen sin la ruta relativa y pongo la imagen referenciada en la ruta raíz en Destinos -> Copiar recursos del paquete dentro de XCode, sin embargo, no puedo hacer que funcione con la ruta relativa como se muestra en mi archivo html. Debe haber una manera de hacer esto, tengo un montón de imágenes, css, javascript archivos que quiero cargar en la webview y me gustaría no tener que tener todo en la raíz y tener que cambiar todas las referencias en mi aplicación web.

 119
Author: RedBlueThing, 2011-06-21

8 answers

Así es como cargar/usar un html local con referencias relativas.

  1. Arrastre el recurso a su proyecto xcode (Arrastré una carpeta llamada www desde mi ventana del finder), obtendrá dos opciones "crear grupos para cualquier carpeta agregada" y "crear referencias de carpetas para cualquier carpeta agregada".
  2. Seleccione la opción "crear referencias de carpeta.." opcion.
  3. Utilice el siguiente código. Debería funcionar a las mil maravillas.

    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"www"]];
    [webview loadRequest:[NSURLRequest requestWithURL:url]];

Ahora todo su pariente enlaces (como img / .gif, js / .js) en el html debe ser resuelto.

Swift 3

    if let path = Bundle.main.path(forResource: "dados", ofType: "html", inDirectory: "root") {
        webView.load( URLRequest(url: URL(fileURLWithPath: path)) )
    }
 285
Author: sdbrain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-18 23:18:16

En Swift:

 func pathForResource(  name: String?, 
                        ofType ext: String?, 
                        inDirectory subpath: String?) -> String?  {

  // **name:** Name of Hmtl
  // **ofType ext:** extension for type of file. In this case "html"
  // **inDirectory subpath:** the folder where are the file. 
  //    In this case the file is in root folder

    let path = NSBundle.mainBundle().pathForResource(             "dados",
                                                     ofType:      "html", 
                                                     inDirectory: "root")
    var requestURL = NSURL(string:path!)
    var request = NSURLRequest(URL:requestURL)

    webView.loadRequest(request)
}
 23
Author: Weles,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-13 12:15:30

Metí todo en una sola línea (malo lo sé) y no tuve problemas con ello:

[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test" 
                                                                                                         ofType:@"html"]
                                                             isDirectory:NO]]];         
 5
Author: PengOne,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-21 05:55:50

Simplemente hago esto:

    UIWebView *webView = [[[UIWebView alloc] init] autorelease];

    NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
    NSURLRequest* request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];

Donde " index.html " relativamente hace referencia a imágenes, CSS, javascript, etc.

 5
Author: Old McStopher,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-16 11:34:08

Respuesta rápida 2.

La Referencia de clase UIWebView desaconseja el uso de WebView.loadRequest (solicitud):

No use este método para cargar archivos HTML locales; en su lugar, use loadHTMLString: baseUrl:.

En esta solución, el html se lee en una cadena. La url del html se usa para calcular la ruta y la pasa como url base.

let url = bundle.URLForResource("index", withExtension: "html", subdirectory: "htmlFileFolder")
let html = try String(contentsOfURL: url)
let base = url.URLByDeletingLastPathComponent
webView.loadHTMLString(html, baseURL: base)
 2
Author: ThisIsNotMe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-09 10:33:15

He vuelto a probar y volver a probar esto, parece que la única manera que puedo conseguir que funcione (ya que tengo algunos archivos en la carpeta img y algunos en js/css, etc...) no es usar una ruta relativa a mi imagen en el html y tener todo referenciado a la carpeta bundle. Qué vergüenza : (.

<img src="myimage.png" />
 0
Author: Matt Palmerlee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-27 19:35:42

La respuesta de@sdbrain en Swift 3:

    let url = URL.init(fileURLWithPath: Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "www")!)
    webView.loadRequest(NSURLRequest.init(url: url) as URLRequest)
 0
Author: skornos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-30 09:58:16

En Swift 3.01 usando WKWebView:

let localURL = URL.init(fileURLWithPath: Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "CWP")!)
myWebView.load(NSURLRequest.init(url: localURL) as URLRequest)

Esto se ajusta para algunos de los cambios de sintaxis más finos en 3.01 y mantiene la estructura de directorios en su lugar para que pueda incrustar archivos HTML relacionados.

 -1
Author: Bently Bobo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-22 15:22:51