将文件加载到应用程序本地存储
Posted
技术标签:
【中文标题】将文件加载到应用程序本地存储【英文标题】:Load file to application local storage 【发布时间】:2015-09-21 07:55:58 【问题描述】:是否可以使用 Filemanager 从服务器加载文档、文章等文件并存储在应用程序本地存储中?那么用户如何阅读这些文件呢?他们有权访问该文件夹吗?
【问题讨论】:
当然你可以下载任何类型的文件并将其保存在文档目录中以供任何使用 【参考方案1】:按照以下步骤下载并保存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 中打开文件:
使用webview
NSString *path = [[NSBundle mainBundle] pathForResource:@"document" ofType:@"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
使用UIDocumentInteractionController
。
查看ZoomingPDFViewer 的 Apple 示例代码
【讨论】:
如果我将在我的应用程序中添加一个用户可以从服务器加载书籍的功能,他如何在没有我的应用程序的情况下打开这本书?例如,在某个阅读器应用中打开一本书。 如果它是pdf
文件,那么 iOS 可以在应用内或 iBooks 应用中自动打开它。我需要有关您的服务器文件的更多信息。
服务器上只有照片、doc、docx文件和pdf。
可以使用UIDocumentInteractionController
原生打开文件。
所以没有我的应用程序就无法访问这些文件?类似于 android 中的文件管理器。以上是关于将文件加载到应用程序本地存储的主要内容,如果未能解决你的问题,请参考以下文章
如何从本地 JSON 文件将数据加载到 ViewController [关闭]