Search code examples
iosaudiovideonsdocumentdirectory

ios save audio and video url into document directory


I need to save all of audio and video url's into document directory which comes from the server. i have tried a sample code

NSData *urlData = [NSData dataWithContentsOfURL:[NSURL URLWithString: "http://www.ebookfrenzy.com/ios_book/movie/movie.mp4"]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString  *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath_ = [documentsDirectory stringByAppendingPathComponent:@"/MyFolder"];
NSString *newStr = [@"test" stringByAppendingString:[NSString stringWithFormat:@".mp4"]];
NSString *FilePath = [NSString stringWithFormat:@"%@/%@",dataPath_,newStr];
[urlData writeToFile:FilePath atomically:YES];

The folder is creating in document directory but the video is not saving into the folder.Can anyone help to sort this out.


Solution

  • You should build the path properly and you should do some basic error checking:

    NSData *urlData = [NSData dataWithContentsOfURL:[NSURL URLWithString: @"http://www.ebookfrenzy.com/ios_book/movie/movie.mp4"]];
    if (urlData) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"MyFolder"];
        // Create folder if needed
        [[NSFileManager defaultFileManager] createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:nil];
    
        NSString *filePath = [dataPath stringByAppendingPathComponent:@"test.mp4"];
        if ([urlData writeToFile:filePath atomically:YES]) {
            // yeah - file written
        } else {
            // oops - file not written
        }
    } else {
        // oops - couldn't get data
    }