0

I have an image file saved in the application's temp folder, say IMG.png. I am injecting an HTML string into a UIWebView using:

    NSString *HTML = [NSString stringWithFormat:
                     @"<body><h2>%@</h2><img src=\"%@\"></img><p>%@</p>%@</body>",
                     title, image, body];

    [webView loadHTMLString:HTML baseURL:[NSURL URLWithString:HOST]];

I tried many combinations of paths for the NSString image, but I cannot get this WebView to load my local image properly.

Can you please help me?

Here's what I use to save my image in the temp folder:

[self saveImage:result withFileName:post.title ofType:@"jpg" inDirectory:NSTemporaryDirectory()];

which relies on:

-(void) saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {

    if ([[extension lowercaseString] isEqualToString:@"png"]) {
        [UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"png"]] options:NSAtomicWrite error:nil];
    } else if ([[extension lowercaseString] isEqualToString:@"jpg"] || [[extension lowercaseString] isEqualToString:@"jpeg"]) {
        [UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"jpg"]] options:NSAtomicWrite error:nil];
    } else {
        NSLog(@"Image Save Failed\nExtension: (%@) is not recognized, use (PNG/JPG)", extension);
    }
}
4

2 回答 2

0
     [webView loadHTMLString:HTML baseURL:[NSURL URLWithString:HOST]]; //the 'HOST' must be your application's temp folder
于 2012-12-06T02:50:27.817 回答
0

尝试使用 NSURL 组合文件 URL:

NSURL *url = [NSURL fileURLWithPath:[[NSTemporaryDirectory() stringByAppendingPathComponent:@"filename"] stringByAppendingPathExtension:@"jpg"]];
NSString *image = [url absoluteString];

(假设您的图像文件名是“filename.jpg”)

应该导致类似:

file://localhost/private/var/mobile/Applications/E754629C-4163-4829-9D10-89D55A61264E/tmp/filename.jpg

希望这可以帮助。

于 2012-12-06T03:17:07.613 回答