IOS:如何在UIWebview中加载本地文件,例如:.png,.doc,.pdf等

时间:2013-12-18 06:36:39

标签: ios iphone ios6 uiwebview uiimageview

我需要在uiwebview中显示png,pdf,doc等本地文件。任何人都可以帮助如何将本地URL加载到webview中并在webview中显示该文件..

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *manager = [NSFileManager defaultManager];
NSString *tempUrlString = [NSString stringWithFormat:@"%@/0_iphone.png",documentsDirectory];

enter image description here

4 个答案:

答案 0 :(得分:4)

您可以使用<img>标记将图片加载到UIWebView

NSString *imagePath  = [[NSBundle mainBundle] pathForResource:@"yourImage" ofType:@"png"];
NSString *htmlString = [NSString stringWithFormat:@"<html><body><img src=\"file://%@\"></body></html>",imagePath];
[myWebView loadHTMLString:htmlString baseURL:nil];

编辑:

要从文档目录加载图像,您只需要更改上面代码中的图像路径,而不是其他任何内容。

NSArray *docPaths            = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [docPaths objectAtIndex:0];
NSString  *imagePath         = [documentsDirectory stringByAppendingPathComponent:@"/yourImage.png"];

答案 1 :(得分:4)

从您的捆绑包中加载文件:

  NSString * html = [[NSString alloc] initWithFormat:@"<img src=\"file://%@\"/>", filename];

 [self.webView loadHTMLString:newhtml  baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]]];

从文档目录加载

NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask ,YES );
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"index.pdf"];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]]

答案 2 :(得分:2)

检查一下......

UIImage *cameraImage = [UIImage imageNamed:@"YourImageName"];

NSData *myData = UIImagePNGRepresentation(cameraImage);

[self.webview loadData:myData MIMEType:@"image/png" textEncodingName:nil baseURL:nil];

答案 3 :(得分:0)

您只需加载UIWebView中的任何文件并将其作为NSURL

传递即可
NSURL *url = [NSURL URLWithString:@"your_FIle_name_with_path"]; // Use NSDocumentsDirectory to get local files.
NSURLRequest *requestURL = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:requestURL];