简体   繁体   中英

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM