Save video URL to Core Data
cocoa-touch, ios, objective-c, uiimagepickercontroller
Solution
Don't create path like this:
NSString *tempPath = [NSString stringWithFormat:@"%@/vid%d%@%@.mp4", documentsDirectory, random, self.currentAthlete.first, self.currentAthlete.last];
create like this:
NSString *tempPath = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:@"vid%d%@%@.mp4", random, self.currentAthlete.first, self.currentAthlete.last]];
Problem
In my app, I utilize the UIImagePickerController to record a video. I then save the video URL from the camera roll into core data, and whenever I want to play it, I pull the URL and do so. However, when the video is deleted from the photos app, it still plays for a couple of days. When it is not deleted from the photos app, it is still deleted after a couple of days. How can I save the video into my app's documents, and save a url to it into core data? Here is what I am using currently (It doesnt work): Here is the zip file that doesn't work: http://jmp.sh/v/w4gE5SXNiRd0d7tasc3U Here is the zip file that now works without errors: http://jmp.sh/v/tzyJU3nlc1qOPI9ZzDTF ``` - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType]; // Handle a movie capture if (CFStringCompare((__bridge_retained CFStringRef)mediaType, kUTTypeMovie, 0) == kCFCompareEqualTo) { NSString *moviePath = [NSString stringWithFormat:@"%@", [[info objectForKey:UIImagePickerControllerMediaURL] path]]; NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL]; NSData *videoData = [NSData dataWithContentsOfURL:videoURL]; AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; _managedObjectContext = [appDelegate managedObjectContext]; Video *video = [NSEntityDescription insertNewObjectForEntityForName:@"Video" inManagedObjectContext:_managedObjectContext]; [video setVideoData:videoData]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; int random = arc4random() % 1000; //[documentsDirectory stringByAppendingFormat:@"/vid1.mp4"] NSString *tempPath = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:@"vid%d%@%@.mp4", random, self.currentAthlete.first, self.currentAthlete.last]]; BOOL success = [videoData writeToFile:tempPath atomically:NO]; if (success == FALSE) { NSLog(@"Video was not successfully saved."); } else{ [video setVideoURL:[NSString stringWithFormat:@"%@", tempPath]]; } NSError *error = nil; if (![_managedObjectContext save:&error]) { } if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(moviePath)) { UISaveVideoAtPathToSavedPhotosAlbum(moviePath, self, @selector(video:didFinishSavingWithError:contextInfo:), nil); } } [self dismissViewControllerAnimated:YES completion:nil]; } ```