如何从url下载video并将其保存到iOS中的文档目录?

如何从url下载video并将其保存到iOS中的文档目录

使用这个代码它正在我当前的项目中工作

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

您可以使用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"); } } }); } 

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

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

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

如果您使用这些术语进行search,则应该可以find说明这两个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) }) } }) }