ios - 将文件加载到应用程序本地存储

标签 ios swift nsfilemanager

是否可以使用 Filemanager 从服务器加载文档、文章等文件并将它们存储在应用程序本地存储中?那么用户如何阅读这些文件呢?他们有权访问该文件夹吗?

最佳答案

按照以下步骤在 NSDocumentDirectory 中下载和保存文件

// Determine local file path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [NSString stringWithFormat:@"%@/%@", [paths objectAtIndex:0],@"fileName.doc"];   //it could be any file type

// Download and write to file
NSURL *url = [NSURL URLWithString:@"http://www.filePathFromServerLocation.com"];

//and write to file
NSData *urlData = [NSData dataWithContentsOfURL:url];
[urlData writeToFile:filePath atomically:YES];

这样你的文件将保存在 filePath 中,你可以在以后以任何你喜欢的方式使用它。

在 iOS 中打开一个文件:

  1. 使用webview

    NSString *path = [[NSBundle mainBundle] pathForResource:@"document" ofType:@"pdf"];
    NSURL *targetURL = [NSURL fileURLWithPath:path];
    NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
    [webView loadRequest:request];
    
  2. 使用 UIDocumentInteractionController

  3. 查看 ZoomingPDFViewer 的 Apple 示例代码

关于ios - 将文件加载到应用程序本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32690056/

相关文章:

ios - 使用 NSOutputstream 有什么好处?

c# - MonoTouch 的性能问题?

ios - 审核前更新 App Store 提交

swift - Google 语音 API 立即超时

objective-c - 如何确定 NSURL 是否是一个目录

cocoa - 访问 Mac OS X Lion 中的用户脚本目录

ios - Tableview获取索引超出空数组范围

ios - 如何解决xcode中的循环依赖错误

ios - 控制iOS应用程序的版本

ios - MVVM 通用网络架构