如何从网址下载视频并将其保存到iOS中的文档目录?

Pra*_*sha 2 objective-c ios

如何从网址下载视频并将其保存到iOS中的文档目录中

Kal*_*era 24

使用此代码,它在我当前的项目中工作

-(void)DownloadVideo
{
//download the file in a seperate thread.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"Downloading Started");
NSString *urlToDownload = @"http://www.somewhere.com/thefile.mp4";
NSURL  *url = [NSURL URLWithString:urlToDownload];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
    {
    NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString  *documentsDirectory = [paths objectAtIndex:0];

    NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"thefile.mp4"];

    //saving is done on main thread
    dispatch_async(dispatch_get_main_queue(), ^{
        [urlData writeToFile:filePath atomically:YES];
        NSLog(@"File Saved !");
    });
    }

});
}
Run Code Online (Sandbox Code Playgroud)


Raj*_*071 5

您可以使用GCD下载它.

-(void)downloadVideoAndSave :(NSString*)videoUrl
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        NSData *yourVideoData=[NSData dataWithContentsOfURL:[NSURL URLWithString:videoUrl]];

        if (yourVideoData) {
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];

            NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"video.mp4"];

            if([yourVideoData writeToFile:videpPath atomically:YES])
            {
                NSLog(@"write successfull");
            }
            else{
                NSLog(@"write failed");
            }
        }
    });
}
Run Code Online (Sandbox Code Playgroud)