【问题标题】:Load image in local HTML file — UIWebView在本地 HTML 文件中加载图像 - UIWebView
【发布时间】:2012-12-08 17:22:06
【问题描述】:

我正在开发一个需要打开远程 html 文件并使用本地图像的 Iphone 应用程序。 我找到了这个答案,这对我来说是完美的解决方案:

iOS WebView remote html with local image files

但问题是,当我尝试加载更多图像时,此解决方案仅加载第一张图像,如下所示:

<html>
<body>
    <h1>we are loading a custom protocl</h1>
    <b>image?</b><br/>
    <img src="myapp://image1.png" />
<img src="myapp://image1.png" />
<img src="myapp://image2.png" />
<img src="myapp://image3.png" />
<body>
</html>

页面将正确显示第一张图片,但其他图片将显示第一张的来源。

【问题讨论】:

  • 您为实现自定义协议的代码发布的链接被硬编码为从主包加载“image1.png”。您需要从请求 URL 中提取图像文件名并使用它。
  • @XJones 代码加载第一个图像,名称不只是 img1,这意味着代码可以提取文件名
  • 我非常喜欢看到答案。

标签: iphone objective-c ios


【解决方案1】:

为什么要使用自定义协议实现在 html 文件中加载本地图像?

您可以轻松地将 html 的根设置为以下内容:

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

这将从您的包中加载所有图像文件。

或者,您可以使用 webview 委托覆盖加载调用,如下所示:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

并且可以完全自定义加载文件的方式和位置。

【讨论】:

    【解决方案2】:

    你可以在 iOS WebView remote html with local image files 但是,为每个图像使用不同的自定义协议名称 例如

    <html>
    <body>
        <h1>we are loading a custom protocl</h1>
        <b>image?</b><br/>
        <img src="myapp://image1.png" />
    <img src="myapp1://image1.png" />
    <img src="myapp2://image2.png" />
    <img src="myapp3://image3.png" />
    <body>
    </html>
    

    然后询问canInitWithRequest方法中使用了哪个协议名,就可以知道startLoading方法中要加载哪个图片了。

    注意:canInitWithRequest 是一个类方法,因此您可以在canInitWithRequest 方法中声明一个静态变量来保存图像文件名

    【讨论】:

      【解决方案3】:

      WKWebView 不允许直接从文件存储(文档目录)访问文件,要从文档目录访问文件必须使用loadFileURL:allowingReadAccessToURL: 方法,下面是我的代码。

      在 ViewDidLoad 中

      //Get Document directory path
          NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
          NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
      
          //Get html from bundle and save it to document directory
          NSURL *url = [[NSBundle mainBundle] URLForResource: @"fileupload" withExtension: @"html"];
          NSData *data = [[NSData alloc] initWithContentsOfFile:[url path]];
          [data writeToFile:[documentsPath stringByAppendingPathComponent:@"fileupload.html"] atomically:YES];
      
          //Get image and save it to document directory
          UIImage *image = [UIImage imageNamed:@"yoga.png"];
          NSData *pngData = UIImagePNGRepresentation(image);
          filePath = [documentsPath stringByAppendingPathComponent:@"yoga.png"]; //Add the file name
          [pngData writeToFile:filePath atomically:YES]; //Write the file
          filePath = [self documentsPathForFileName:@"yoga.png"];
          NSLog(@"File path: %@", [self documentsPathForFileName:@"yoga.png"]);
      
          NSURL *fileurl = [NSURL fileURLWithPath:[documentsPath stringByAppendingPathComponent:@"fileupload.html"]];
          [webView loadFileURL:fileurl allowingReadAccessToURL:[NSURL fileURLWithPath:documentsPath]];
      

      上面的代码将图像从bundle保存到文档目录,还保存了一个html文件(将使用img标签加载图像)。

      在didFinishNavigation下方:

      //Sending Path to javascript
          [webView evaluateJavaScript:[NSString stringWithFormat:@"upload('%@')", filePath] completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
              NSLog(@"Java script called");
          }];
      

      获取文件url的实用方法

      - (NSString *)documentsPathForFileName:(NSString *)name
      {
          NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
          NSString *documentsPath = [paths objectAtIndex:0];
      
          NSURL *url = [NSURL fileURLWithPath:[documentsPath stringByAppendingPathComponent:name]];
      
          return [url absoluteString];
      }
      

      最后是 HTML 文件,该文件具有从 webview 获取路径和加载图像的方法

      <html>
          <head><title>demo</title>
              <script>
      
                  function upload(path)
                  {
                      alert(path);
                      /*
                       var URI = "data:image/png;base64,"+path;
                       convertURIToImageData(URI).then(function(imageData) {
                       // Here you can use imageData
                       console.log(imageData);
                       });
                       */
                      var img = document.createElement("IMG");
                      img.src = path;//URI;
                      img.border = 1;
                      img.height = 750;
                      img.width = 900;
                      document.getElementById('imageDiv').appendChild(img);
                  }
      
              function convertURIToImageData(URI) {
                  return new Promise(function(resolve, reject) {
                                     if (URI == null) return reject();
                                     var canvas = document.createElement('canvas'),
                                     context = canvas.getContext('2d'),
                                     image = new Image();
                                     image.addEventListener('load', function() {
                                                            canvas.width = image.width;
                                                            canvas.height = image.height;
                                                            context.drawImage(image, 0, 0, canvas.width, canvas.height);
                                                            resolve(context.getImageData(0, 0, canvas.width, canvas.height));
                                                            }, false);
                                     image.src = URI;
                                     });
              }
                  </script>
          </head>
          <body>
              <p><h1>This is a Demo !!!</h1></p>
              <div id="imageDiv"></div>
          </body>
      </html>
      

      以上方法是我发现从文档目录加载图像/文件的唯一方法。

      您还可以以数据 url 的形式发送您的图像/文件并将其传递给 javascript 方法(已经写在 html 文件中),只需将您的图像转换为 NSData 并将基本编码为字符串,javascript 会将数据 url 转换为图像对象本身。

      UIImage 到数据 URL 的转换:

      UIImage *img = [UIImage imageNamed:@"yoga.png"];
      NSData *data = UIImageJPEGRepresentation(img, 0.90);
      data = [data base64EncodedDataWithOptions:0];
      NSString *dataurl = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
      

      干杯!!!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-18
        • 2011-06-20
        • 1970-01-01
        • 2011-10-20
        相关资源
        最近更新 更多