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

时间:2014-04-02 10:55:41

标签: ios objective-c

如何从网址下载视频并将其保存到iOS

中的文档目录中

4 个答案:

答案 0 :(得分:23)

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

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

});
}

答案 1 :(得分: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");
            }
        }
    });
}

答案 2 :(得分:1)

您可以使用NSURLConnection方法sendAsynchronousRequest:queue:completionHandler:

一个方法将整个文件下载到NSData对象中,并在完成后调用完成处理程序方法。

如果您可以编写需要iOS 7或更高版本的应用,您还可以使用新的NSURLSession API。这提供了更多功能。

如果您使用这些术语进行搜索,您应该能够找到说明这两个API的教程和示例应用程序。

答案 3 :(得分:-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)
            })

        }
    })

}