【问题标题】:Open downloaded files in webview in iphone在 iphone 的 webview 中打开下载的文件
【发布时间】:2011-07-29 18:23:59
【问题描述】:

我是 iphone 开发新手。我正在开发一个 iphone 应用程序,在该应用程序中我使用以下代码使用 Web 服务下载文件:

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath =  [paths objectAtIndex:0];
NSString *fileLoc = [basePath stringByAppendingString:@"/filename.pdf"];
NSData *fileData = [self decodeBase64WithString:soapResults];
[fileData writeToFile:fileLoc atomically:YES];

我的文件在路径中:/Users/myusername/Library/Application Support/iPhone Simulator/4.0/Applications/7A627E64-DEAB-40FA-BE04-35ED50580B65/filename.pdf

如何使用 uiwebview 打开这个文件???我试过这个:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath =  [paths objectAtIndex:0];
NSString *fileLoc = [basePath stringByAppendingString:@"/filename"];
[self loadDocument:fileLoc inView:mywebview];

我的 loadDocument 方法是:

-(void)loadDocument:(NSString*)documentName inView:(UIWebView*)webView
{
NSString *path = [[NSBundle mainBundle] pathForResource:documentName ofType:@"pdf"];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];  
}

但它显示错误...我认为位置是问题..我如何在模拟器和原始设备中找到路径???

请帮帮我...

【问题讨论】:

    标签: iphone objective-c ios uiwebview


    【解决方案1】:

    pathForResource:ofType: 只能用于加载资源文件,这些文件是作为应用程序包的一部分提供的。您正在尝试从 Documents 目录加载下载的文件。所以你应该能够做到

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath =  [paths objectAtIndex:0];
    NSString *fileLoc = [basePath stringByAppendingString:@"/filename.pdf"];
    NSURL *url = [NSURL fileURLWithPath:fileLoc];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request]; 
    

    【讨论】:

    • 是的。 NSSearchPathForDirectoriesInDomains 为设备和模拟器返回适当的路径。
    • @cduhn 我正在下载带有时间戳的 pdf 文件,如下所示:/Documents/myPDF.pdf1382698338.78128 那么现在我该如何追加路径组件??
    【解决方案2】:

    您遇到的错误是什么?你的loadDocument 方法是什么样的?您应该像这样将文档加载到 WebView 中:

    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:fileLoc]]];
    

    【讨论】:

    • 对不起,我忘了添加 loadDocument 方法.. 现在我添加了.. 请检查.. 和你说的一样......我的错误是:“[NSURL initFileURLWithPath:]: nil string参数”在控制台...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-05
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 2018-07-25
    相关资源
    最近更新 更多