如何在iOS中从URL下载视频并将其保存到文档目录中
使用这段代码,在我的当前项目中它是有效的。
-(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 !");
});
}
});
}
-(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");
}
}
});
}
sendAsynchronousRequest:queue:completionHandler:
。该方法将整个文件下载到NSData对象中,并在完成后调用您的完成处理程序方法。NSURLSession
API。那提供了更多的功能。你也可以在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)
})
}
})
}