Cómo save el file de video en el directory de documentos

Estoy capturando video usando el siguiente código:

UIImagePickerController *ipc = [[UIImagePickerController alloc] init]; ipc.sourceType = UIImagePickerControllerSourceTypeCamera; ipc.delegate = self; //need to handle delegates methods // ipc.allowsEditing = YES; ipc.videoQuality = UIImagePickerControllerQualityTypeMedium; ipc.videoMaximumDuration = 30.0f; // 30 seconds //temporary duation of 30 seconds for testing ipc.mediaTypes = [NSArray arrayWithObject:@"public.movie"]; // ipc.mediaTypes = [NSArray arrayWithObjects:@"public.movie", @"public.image", nil]; [self presentModalViewController:ipc animated:YES]; //this controller allows to record the videos 

y puedo save el video grabado en el álbum usando el siguiente código

 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { // recover video URL NSURL *url = [info objectForKey:UIImagePickerControllerMediaURL]; // check if video is compatible with album BOOL compatible = UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([url path]); // save if (compatible){ UISaveVideoAtPathToSavedPhotosAlbum([url path], self, @selector(video:didFinishSavingWithError:contextInfo:), NULL); NSLog(@"saved!!!! %@",[url path]); } [self dismissModalViewControllerAnimated:YES]; [picker release]; } 

pero necesito recuperar ese file del álbum y necesito almacenarlo en el directory de documentos?

Guardar el video en el directory de documentos es el siguiente:

 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL]; NSData *videoData = [NSData dataWithContentsOfURL:videoURL]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *tempPath = [documentsDirectory stringByAppendingFormat:@"/vid1.mp4"]; BOOL success = [videoData writeToFile:tempPath atomically:NO]; [picker dismissModalViewControllerAnimated:YES]; } 

Aquí está el código rápido si alguien lo necesita en el futuro:

 func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { let videoURL = info[UIImagePickerControllerMediaURL] as! NSURL let videoData = NSData(contentsOfURL: videoURL) let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) let documentsDirectory: AnyObject = paths[0] let dataPath = documentsDirectory.stringByAppendingPathComponent("/vid1.mp4") videoData?.writeToFile(dataPath, atomically: false) self.dismissViewControllerAnimated(true, completion: nil) } 
 #pragma mark - #pragma mark File Names and Paths // Creates the path if it does not exist. - (void)ensurePathAt:(NSString *)path { NSFileManager *fm = [NSFileManager defaultManager]; if ( [fm fileExistsAtPath:path] == false ) { [fm createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:NULL]; } } - (NSString *)documentPath { if ( ! documentPath_ ) { NSArray *searchPaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); documentPath_ = [searchPaths objectAtIndex: 0]; documentPath_=[documentPath_ stringByAppendingPathComponent:@"VideoAlbum"]; [documentPath_ retain]; } return documentPath_; } - (NSString *)audioPath { if ( ! AudioPath_ ) { AudioPath_ = [[self documentPath] stringByAppendingPathComponent:@"Demo"]; NSLog(@"%@",AudioPath_); [AudioPath_ retain]; [self ensurePathAt:AudioPath_]; } return AudioPath_; } -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSString *type = [info objectForKey:UIImagePickerControllerMediaType]; if ([type isEqualToString:(NSString *)kUTTypeVideo] || [type isEqualToString:(NSString *)kUTTypeMovie]) { NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL]; NSData *videoData = [NSData dataWithContentsOfURL:videoURL]; tempPath = [[self audioPath] stringByAppendingFormat:@"/%@.mp4",[NSDate date]]; BOOL success = [videoData writeToFile:tempPath atomically:NO]; NSLog(@"%hhd",success); } [[picker presentingViewController] dismissViewControllerAnimated:YES completion:nil]; } 

Un poco de I + D, esto me funcionó

 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 

{

  NSURL *url = [info objectForKey:UIImagePickerControllerMediaURL]; // Save video to app document directory NSString *filePath = [url path]; NSString *pathExtension = [filePath pathExtension] ; if ([pathExtension length] > 0) { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) ; NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", [filePath lastPathComponent]]]; // Method last path component is used here, so that each video saved will get different name. NSError *error = nil ; BOOL res = [[NSFileManager defaultManager] moveItemAtPath:filePath toPath:localFilePath error:&error] ; if (!res) { NSLog(@"%@", [error localizedDescription]) ; } else { NSLog(@"File saved at : %@",localFilePath); } } 

}

// También cuando tienes que verificar que el mismo video ya existe en el directory de documentos de la aplicación y no quieres crear múltiples copys de él, a continuación, realizaste algunos cambios como a continuación.

 NSURL *url = [info objectForKey:UIImagePickerControllerMediaURL]; NSURL *videoAsset = [info objectForKey:UIImagePickerControllerReferenceURL]; __weak typeof(self) weakSelf = self; ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; [library assetForURL:videoAsset resultBlock:^(ALAsset *asset) { weakSelf.selectedFileName = [[asset defaultRepresentation] filename]; NSLog(@"Video Filename %@",weakSelf.selectedFileName); // Save video to doc directory NSString *filePath = [url path]; NSString *pathExtension = [filePath pathExtension] ; if ([pathExtension length] > 0) { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) ; NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", weakSelf.selectedFileName]]; //check if same video is having its copy in app directory. //so that multiple entries of same file should not happen. BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:localFilePath]; if (!fileExists) { NSError *error = nil ; BOOL res = [[NSFileManager defaultManager] moveItemAtPath:filePath toPath:localFilePath error:&error] ; if (!res) { NSLog(@"%@", [error localizedDescription]) ; } else { NSLog(@"File saved at : %@",localFilePath); weakSelf.filePathURL = [NSURL URLWithString:localFilePath]; } } else { NSLog(@"File exist at : %@",localFilePath); weakSelf.filePathURL = [NSURL URLWithString:localFilePath]; } } } 

}

// Donde weakSelf.selectedFileName & weakSelf.filePathURL son NSString y las properties de tipo NSURL de mi class respectivamente.

Podemos usar el método moveItemAtPath de moveItemAtPath:toPath:error: método para mover el file de video al directory de documentos de nuestra aplicación. Es mas eficiente

También deberíamos get la extensión del file de video y usarlo como extensión de nuestro nombre de file de video local.

 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { [self dismissViewControllerAnimated:YES completion:nil] ; if ([info[UIImagePickerControllerMediaType] isEqualToString:(NSString *)kUTTypeMovie]) { // video NSURL *url = [info[UIImagePickerControllerMediaType] ; NSString *filePath = [url path] ; NSString *pathExtension = [filePath pathExtension] ; if ([pathExtension length] > 0) { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) ; NSString *documentsDirectory = [paths objectAtIndex:0] ; NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"temp.%@", pathExtension]] ; NSError *error = nil ; BOOL res = [[NSFileManager defaultManager] moveItemAtPath:filePath toPath:localFilePath error:&error] ; if (!res) { NSLog(@"%@", [error localizedDescription]) ; } } } } 

Esto funciona para mi.

  videoUrl = [info objectForKey:UIImagePickerControllerMediaURL]; urlString=[urlvideo path]; NSLog(@"path url %@",videoUrl); NSData *videoData = [NSData dataWithContentsOfURL:videoUrl]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *sourcePath = [documentsDirectory stringByAppendingPathComponent:@"yourfilename.mp4"]; [videoData writeToFile:sourcePath atomically:YES]; //Below code will save video to iOS Device ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init]; [library writeVideoAtPathToSavedPhotosAlbum:videoUrl completionBlock:^(NSURL *assetURL, NSError *error){/*notify of completion*/}]; [picker dismissViewControllerAnimated:YES completion:nil]; 

Espero que esto ayude

Esta publicación trata sobre un video grabado, ¿qué tal un video almacenado agregado mediante drag and drop? Estoy tratando de desarrollar una aplicación donde desde el principio debe haber un file de video (test.mov) en el directory de documentos. Sería bueno comprobar la primera vez que se ejecuta la aplicación si existe en este directory y si no hay más videos, cópielo para que siempre haya un video al less.

Al crear el proyecto, agregué el video haciendo "drag and drop" en Xcode para que esté en la list del browser del proyecto con el rest de mis files de proyectos (AppDelegate.h, ViewController.h, ViewController.m … etc.) no estoy seguro cómo get la url de la misma.

  videoURL = info[UIImagePickerControllerMediaURL]as? NSURL print(videoURL!) let urlData=NSData(contentsOf: videoURL as! URL) if((urlData) != nil) { let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let documentDirectory = path.first! as NSString let fileName = "Video.MOV" let PDFPathFileName = documentDirectory.appendingPathComponent(fileName as String) print(PDFPathFileName) DispatchQueue.main.async( execute: { urlData?.write(toFile: PDFPathFileName, atomically: true) }) do { let asset = AVURLAsset(url: videoURL as! URL , options: nil) let imgGenerator = AVAssetImageGenerator(asset: asset) imgGenerator.appliesPrefernetworkingTrackTransform = true let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(0, 1), actualTime: nil) let thumbnail = UIImage(cgImage: cgImage) imgView.image = thumbnail // thumbnail here } catch let error { print("*** Error generating thumbnail: \(error.localizedDescription)") } } self.dismiss(animated: true, completion: nil)