在本地HTML文件中加载图像 - UIWebView

时间:2012-12-21 05:46:56

标签: iphone objective-c ios

我正在研究需要打开远程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>

页面将向右显示第一张图像,但其他图像将显示第一张图像的来源。

3 个答案:

答案 0 :(得分:1)

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

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

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

这将加载捆绑包中的所有图像文件。

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

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

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

答案 1 :(得分:0)

你可以使用相同的想法 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方法中的图像文件名

答案 2 :(得分:0)

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

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

在didFinishNavigation下面:

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

获取文件网址的实用方法

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

干杯!!!