【发布时间】:2015-07-27 00:51:18
【问题描述】:
我的应用程序中有一个场景,我需要使用我的应用程序下载 mp3、pdf、文本文件。
如何使用我的应用程序下载数据以及将数据存储在何处?
【问题讨论】:
-
在
NSDocumentDirectory! -
您好,您可以使用 [this][1] 链接 [1]:stackoverflow.com/questions/13987788/…
标签: ios
我的应用程序中有一个场景,我需要使用我的应用程序下载 mp3、pdf、文本文件。
如何使用我的应用程序下载数据以及将数据存储在何处?
【问题讨论】:
NSDocumentDirectory!
标签: ios
NSString *stringURL = @"http://www.somewhere.com/thefile.png";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.png"];
[urlData writeToFile:filePath atomically:YES];
}
您可以存储在文档目录中,以下是存储图像的示例。以下是存储音频视频文件的链接说明
How to download audio/video files from internet and store in iPhone app?
【讨论】:
文档目录最适合存储数据。
NSString *path = [[self applicationDocumentsDirectory].path
stringByAppendingPathComponent:@"fileName.txt"];
[sampleText writeToFile:path atomically:YES
encoding:NSUTF8StringEncoding error:nil];
- (NSURL *)applicationDocumentsDirectory {
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] lastObject];
}
【讨论】:
这取决于您需要如何处理数据。如果可以重新创建或下载数据,请将其保存在 temp o cacje 目录中。如果数据由用户创建并且必须备份,您可以使用 Documents 与 iCloud 同步。 我建议您阅读 Apple 文档,因为如果您这样做错误,您的应用程序可能会被拒绝。 https://developer.apple.com/library/ios/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html
您可以排除要备份的文件(并存储在 Documents 文件夹中) https://developer.apple.com/library/ios/qa/qa1719/_index.html
【讨论】: