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

3
如何在iOS中从URL下载视频并将其保存到文档目录中
4个回答

26

使用这段代码,在我的当前项目中它是有效的。

-(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 !");
    });
    }

});
}

它可以工作...非常感谢...但问题是它没有显示下载的状态... - Praksha
不会,因为YouTube有自己的政策。 - Kalpit Gajera

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");
            }
        }
    });
}

1
你可以使用NSURLConnection方法sendAsynchronousRequest:queue:completionHandler:。该方法将整个文件下载到NSData对象中,并在完成后调用您的完成处理程序方法。
如果您可以编写需要iOS 7或更高版本的应用程序,则还可以使用新的NSURLSession API。那提供了更多的功能。
如果您使用这些术语搜索,您应该能够找到教程和示例应用程序,以说明两个API。

-1

你也可以在Swift 2.0中实现相同的功能

class func downloadVideo(videoImageUrl:String)
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
        //All stuff here

        let url=NSURL(string: videoImageUrl)
        let urlData=NSData(contentsOfURL: url!)

        if((urlData) != nil)
        {
            let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]

            let fileName = videoImageUrl.lastPathComponent //.stringByDeletingPathExtension

            let filePath="\(documentsPath)/\(fileName)"

            //saving is done on main thread

            dispatch_async(dispatch_get_main_queue(), { () -> Void in

                 urlData?.writeToFile(filePath, atomically: true)
            })

        }
    })

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接