我有一个图像文件保存在应用程序的临时文件夹中,比如IMG.png。我使用以下方法将HTML字符串注入UIWebView:
NSString *HTML = [NSString stringWithFormat:
@"<body><h2>%@</h2><img src=\"%@\"></img><p>%@</p>%@</body>",
title, image, body];
[webView loadHTMLString:HTML baseURL:[NSURL URLWithString:HOST]];
我为NSString image
尝试了很多路径组合,但我无法让这个WebView正确加载我的本地图像。
你能帮帮我吗?
以下是我用于将图像保存在临时文件夹中的内容:
[self saveImage:result withFileName:post.title ofType:@"jpg" inDirectory:NSTemporaryDirectory()];
依赖于:
-(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);
}
}
答案 0 :(得分:0)
[webView loadHTMLString:HTML baseURL:[NSURL URLWithString:HOST]]; //the 'HOST' must be your application's temp folder
答案 1 :(得分: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
希望这有帮助。