user user - 28 days ago 16
Objective-C Question

How to download a file from a folder?

I want to download a file in documentsDirectory in folder "tracks". But if I use this code (file download in documentsDirectory). All work fine

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];


And if I use this code(file download in documentsDirectory in folder "tracks") file is not downloaded

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];


How to download a file in documentsDirectory in folder "tracks"?

Answer

The tracks folder probably doesn't exist yet. You need something like:

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