简体   繁体   中英

How to show an image saved on Documents Directory inside local HTML? iOS

I've this app which needs to store images shown in a webview locally, and show those stored images again inside the same webview.

This what I've gotten so far...

    // After download button clicked... Store image from URL locally
    NSURL  *url = [NSURL URLWithString:myURL];
    NSData *urlData = [NSData dataWithContentsOfURL:url];
    if ( urlData )
    {
        NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString  *documentsDirectory = [paths objectAtIndex:0];

        NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.png"];
        [urlData writeToFile:filePath atomically:YES];
    }

    // Get image path from Documents Directory
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"filename.png"];

    // Display local html page                 
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"revistasPhotoswipe" ofType:@"html" inDirectory:@"www"]];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [_webView loadRequest:requestObj];

And in html file there's just a tag to show the image

   <html>
   <head></head>
   <body><img src='filename.png' /></body>
   </html>

Which is the right way to communicate the Documents Dir, with App Bundle and the HTML files to make this work? Another approach?

You can't use <body><img src='filename.png' /></body> because it references an object on a localserver that doesn't exist. You have a couple of options:

1. Javascript

A milliseconds after the page has loaded you should tell your webview to evaluate a javascript function. document["pictureIdFromProgam"].src = searchPic.src; as well as declaring your image element with <img src='throw.imgNotSet' id='pictureIdFromProgam'/>

2. String Manipulatoin

Another (less desirable, but quicker) option is to have your HTML file coded into an NSString and inserting the img link by using either replacing or %@s

Insertion:

[NSString stringWithFormat:@"<html><blah blah blah/><img src=%@/>",imagePathAsString];

and then you will be able to tell your webview to load the nsstring which contains the updated web content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM