如何从文件夹下载文件?

时间:2016-11-08 16:34:32

标签: ios objective-c directory

我想在文件夹“tracks”中的documentsDirectory中下载一个文件。但是,如果我使用此代码(文件下载在documentsDirectory中)。一切正常

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Chapter.mp3"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:false];

NSString *stringURL = @"link";
NSURL  *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
[urlData writeToFile:filePath atomically:YES];

如果我使用此代码(文件下载在文件夹“track”中的文件目录中),则不会下载文件

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"tracks/Chapter.mp3"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:false];

NSString *stringURL = @"link";
NSURL  *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
[urlData writeToFile:filePath atomically:YES];

如何下​​载文件夹“tracks”中的documentsDirectory中的文件?

1 个答案:

答案 0 :(得分:0)

track文件夹可能尚不存在。你需要这样的东西:

NSError *error = nil;
NSString *tracksPath = [documentsDirectory stringByAppendingPathComponent:@"tracks];
if (![[NSFileManager defaultManager] fileExistsAtPath:tracksPath]) {
    [[NSFileManager defaultManager] createDirectoryAtPath:tracksPath withIntermediateDirectories:NO attributes:nil error:&error];
}