【问题标题】:How to open locally saved PDF file in an Objective C如何在Objective C中打开本地保存的PDF文件
【发布时间】:2018-01-23 14:47:28
【问题描述】:

我正在尝试将 PDF 文件保存到本地存储。

我以这种方式保存文件,在我看来一切都很好。

//Get path directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

//Create PDF_Documents directory
documentsDirectory = [documentsDirectory stringByAppendingPathComponent:@"PDF_Documents"];
[[NSFileManager defaultManager] createDirectoryAtPath:documentsDirectory withIntermediateDirectories:YES attributes:nil error:nil];

filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory, tastingName];

[tastingNotesData writeToFile:filePath atomically:YES];

这样我尝试获取文件

tastingPath = /var/mobile/Containers/Data/Application/4255D8B0-33F5-47AA-ABFA-CCC3691DA033/Documents/PDF_Documents/39e0afcdb56240c2a65ab9e136377b32.pdf;

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[self.productModel.tastingPath lastPathComponent]];

NSData *data2 = [[NSFileManager defaultManager] contentsAtPath:path];

NSLog(@"tasting notes %@", data2);

最后文件会显示在 UIWebView 中。

我做错了什么?

【问题讨论】:

  • link 可能有帮助
  • 为什么你在一个地方正确地使用stringByAppendingPathComponent附加一个路径,然后使用stringWithFormat附加更多的路径?不要使用stringWithFormat 构建路径。
  • Hooda PDF 是从 API 保存的。保存文件的 URL 高几行,从 testingPath 开始
  • rmaddy 我在另一个主题中找到了这个解决方案,有人写道它工作得很好,这就是我使用它的原因
  • @kajz3reczka 仅仅因为它恰好起作用并不能使它成为正确的解决方案。使用stringByAppendingPathComponent 构建路径,而不是stringWithFormat。此外,为什么要不一致并使用两种不同的方式附加到路径?使用一种(正确的)方式并保持一致。它使您的代码更易于阅读和维护,并减少错误。

标签: ios objective-c pdf local-storage


【解决方案1】:

问题很简单。在您尝试阅读 PDF 文件时,您没有包含路径的 PDF_Documents 部分。或者您没有附加文件名。不能100%确定哪一部分是错的。这取决于[self.productModel.tastingPath lastPathComponent]的值是多少。

【讨论】:

  • tastingPath 包含 PDF_Document 部分。 [Self.productModel.tastingPath lastPathComponent] 正好是 39e0afcdb56240c2a65ab9e136377b32.pdf
  • 但是你没发现问题吗?您只能访问 lastPathComponenttastingPath。所以你忽略了路径的PDF_Document 部分。
  • 天哪!你有权利。非常感谢 :) 现在一切正常。
  • 很高兴为您提供帮助。请不要忘记接受可以解决您问题的答案。它让人们知道您的问题已得到解答。
猜你喜欢
  • 1970-01-01
  • 2015-12-17
  • 2012-07-21
  • 2014-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-19
相关资源
最近更新 更多