Saving video after tapping use in UIImagePickerController - objective-c

I am have an app that calls UIImagePickerController, and you take video using the controller. After you take the video, I want the video to be saved into the camera roll after clicking use in the UIImagePickerController.
Can you help me?
Oh, and UIImagePickerController comes with the option to switch to video, default photo. I want this to be only video, not photo.
My current code is :
picker.sourceType=UIImagePickerControllerCameraCaptureModeVideo;
picker.mediaTypes=[UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];

Once you have implemented the following delegate method, pressing the 'Use' button will save your recorded video to the camera roll.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
NSURL *recordedVideoURL= [info objectForKey:UIImagePickerControllerMediaURL];
if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:recordedVideoURL]) {
[library writeVideoAtPathToSavedPhotosAlbum:recordedVideoURL
completionBlock:^(NSURL *assetURL, NSError *error){}
];
}
[library release];
}
Use the following to set the capture mode to video :
imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
Here is the complete code that I use to launch the image picker for video recording :
UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
imagePickerController.mediaTypes = [NSArray arrayWithObject:(NSString *)kUTTypeMovie];
imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePickerController.showsCameraControls = YES;
imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
imagePickerController.delegate = self;
imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceFront;
[self presentModalViewController:imagePickerController animated:YES];
}

I was trying to save the video using the absoluteURL of the URL but it didn't work
NSURL *mediaURL = [info objectForKey: UIImagePickerControllerMediaURL];
UISaveVideoAtPathToSavedPhotosAlbum(mediaURL.absoluteString, self, #selector(video:didFinishSavingWithError:contextInfo:), nil);
It finally worked using the path property:
UISaveVideoAtPathToSavedPhotosAlbum([mediaURL path], self, #selector(video:didFinishSavingWithError:contextInfo:), nil);
Hope it helps anyone.

From the UIImagePickerControllerDelegate class reference:
To save a still image to the user’s Camera Roll album, call the
UIImageWriteToSavedPhotosAlbum function from within the body of the
imagePickerController:didFinishPickingMediaWithInfo: method. To save a
movie to the user’s Camera Roll album, instead call the
UISaveVideoAtPathToSavedPhotosAlbum function. These functions,
described in UIKit Function Reference, save the image or movie only;
they do not save metadata.
Your UIImagePickerControllerDelegate may look something like this...
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info objectForKey:#"mediaType"];
if (![mediaType isEqualToString:kUTTypeMovie])
return;
NSURL *mediaURL = [info objectForKey:#"mediaURL"];
UISaveVideoAtPathToSavedPhotosAlbum(mediaURL.absoluteString, self, #selector(video:didFinishSavingWithError:contextInfo:), NULL);
}
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo: (void *)contextInfo
{
if (!videoPath && error)
{
NSLog(#"Error saving video to saved photos roll: %#, %#", error, [error userInfo]);
// Handle error;
return;
}
// Video was saved properly. UI may need to be updated here.
}
Notice that I've implemented the completion selector for UISaveVideoToSavedPhotosAlbum(). If it were to fail for any reason, the error would be reported here and you can then handle it appropriately.

Related

How to record video from iPhone camera in iOS 9 objective c?

hello I need to build app that record video from iPhone camera.
I search in the net and not found notting that works in iOS 9.
I get this code from this git project :
https://github.com/versluis/Video-Recorder
This code open camera but not allow Me to take a video.
- (IBAction)recordButton:(id)sender {
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIImagePickerController *picker = [[UIImagePickerController alloc]init];
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.delegate = self;
picker.allowsEditing = NO;
NSArray *mediaTypes = [[NSArray alloc]initWithObjects:(NSString *)kUTTypeMovie, nil];
picker.mediaTypes = mediaTypes;
[self presentViewController:picker animated:YES completion:nil];
} else {
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:#"I'm afraid there's no camera on this device!" delegate:nil cancelButtonTitle:#"Dang!" otherButtonTitles:nil, nil];
[alertView show];
}
}
- (IBAction)playbackButton:(id)sender {
// pick a video from the documents directory
NSURL *video = [self grabFileURL:#"video.mov"];
// create a movie player view controller
MPMoviePlayerViewController * controller = [[MPMoviePlayerViewController alloc]initWithContentURL:video];
[controller.moviePlayer prepareToPlay];
[controller.moviePlayer play];
// and present it
[self presentMoviePlayerViewControllerAnimated:controller];
}
#pragma mark - Delegate Methods
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
// user hit cancel
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
// grab our movie URL
NSURL *chosenMovie = [info objectForKey:UIImagePickerControllerMediaURL];
// save it to the documents directory
NSURL *fileURL = [self grabFileURL:#"video.mov"];
NSData *movieData = [NSData dataWithContentsOfURL:chosenMovie];
[movieData writeToURL:fileURL atomically:YES];
// save it to the Camera Roll
UISaveVideoAtPathToSavedPhotosAlbum([chosenMovie path], nil, nil, nil);
// and dismiss the picker
[self dismissViewControllerAnimated:YES completion:nil];
}
- (NSURL*)grabFileURL:(NSString *)fileName {
// find Documents directory
NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
// append a file name to it
documentsURL = [documentsURL URLByAppendingPathComponent:fileName];
return documentsURL;
}
Ray gave pretty good tutorial about this. Hope it helped.

iphone sdk how to get complete images from photo library?

Hi i want the images what ever saved in photo library.Using assert library can i get complete images stored in photo library.If yes,can anyone please tell me the code for that.Thanks in advance.
Super easy to do!
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[imagePicker setDelegate:self];
[self presentModalViewController:imagePicker animated:YES];
and
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissModalViewControllerAnimated:YES];
[picker release];
// Edited image works great (if you allowed editing)
//myUIImageView.image = [info objectForKey:UIImagePickerControllerEditedImage];
// AND the original image works great
//myUIImageView.image = [info objectForKey:UIImagePickerControllerOriginalImage];
// AND do whatever you want with it, (NSDictionary *)info is fine now
//UIImage *myImage = [info objectForKey:UIImagePickerControllerEditedImage];
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
[customImageView setImage:image];
customImageView.contentMode = UIViewContentModeScaleAspectFill;
}
got this code from stackoverflow, didn't save the URL, sorry.

UIImagePickerController issue?

This is my code to present the UIImagePickerController:
// Show the media browser with our settings, then the browser will call our delegate if needed
- (BOOL) startMediaBrowserFromViewController: (UIViewController*) controller
usingDelegate: (id <UIImagePickerControllerDelegate,
UINavigationControllerDelegate>) delegate {
if (([UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeSavedPhotosAlbum] == NO)
|| (delegate == nil)
|| (controller == nil))
return NO;
UIImagePickerController *mediaUI = [[[UIImagePickerController alloc] init] autorelease];
mediaUI.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
// Check for images type
NSArray * availableTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
BOOL imgsOnlyAvailable = NO;
// Check if we have only images
for (int i = 0; i < [availableTypes count]; i++) {
// Convert the type
CFStringRef type = (CFStringRef) [availableTypes objectAtIndex:i];
if (CFStringCompare ((CFStringRef) type, kUTTypeImage, 0) == kCFCompareEqualTo) {
// We have images
imgsOnlyAvailable = YES;
break;
}
}
// Check if they are available
if (imgsOnlyAvailable == NO)
return NO;
// Displays only saved pictures from the Camera Roll album.
mediaUI.mediaTypes = [NSArray arrayWithObject:(id) kUTTypeImage];
// Hides the controls for moving & scaling pictures, or for
// trimming movies. To instead show the controls, use YES.
mediaUI.allowsEditing = NO;
mediaUI.delegate = delegate;
[controller presentModalViewController: mediaUI animated: YES];
return YES;
}
// Picker delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
UIImage *originalImage;
// Handle a still image picked from a photo album
if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0)
== kCFCompareEqualTo) {
originalImage = (UIImage *) [info objectForKey:
UIImagePickerControllerOriginalImage];
// Set image
self.imgPic.image = originalImage;
// Now set the button to enabled
self.btnToText.enabled = YES;
}
// Hide picker selector
[[picker parentViewController] dismissModalViewControllerAnimated: YES];
[picker release];
}
The problem is whenever I try to click an image in the UIImagePickerController nothing happens (usually it chooses the image then will dismiss the Controller)
Is there any reason why things are going wrong like this?
Thanks!
// Select the image
- (IBAction)btnSelectFileTouchUp:(id)sender {
// Start the media browser
if ([self startMediaBrowserFromViewController:self usingDelegate:self] == NO) {
// Can't open the media browser
UIAlertView * alrt = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Can't open the photo media browser in this device" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alrt show];
[alrt release];
}
}
Check out the documentation for parentViewController in the UIViewController Class Reference. Specifically this little tidbit.
Prior to iOS 5.0, if a view did not have a parent view controller and
was being presented modally, the view controller that was presenting
it would be returned. This is no longer the case. You can get the
presenting view controller using the presentingViewController
property.
In this instance, I expect that parentViewController is nil on iOS 5 and that is why the controller will not dismiss. Try replacing parentViewController with presentingViewController.
Update: You'll have to check for the existence of presentingViewController on UIViewController to provide behavior for iOS versions < 5.0.
UIViewController *dismissingController = nil;
if ([self respondsToSelector:#selector(presentingViewController)])
dismissingController = self.presentingViewController;
else
dismissingController = self.parentViewController;
[dismissingController dismissModalViewControllerAnimated:YES];

UIImage Causing Views All Throughout the iPhone to Turn Black

Alright, this problem is rather bizarre, and I'm 99% positive at this point it's not a retain/release error. Basically I'm using UIImagePickerController to grab an image from either the library or the camera, but the resulting image causes some... strange things to happen. Though it's laggy to pull the image up in a detail view controller containing a UIImageView, the real problem is that if I repetitively pull up the view controller and dismiss it, eventually parts of the image will have disappeared!!! More disturbingly, if I attempt to pull it up again after this has happened, the whole image will have turned black, and other UIViews throughout both my App AND the iPhone itself will either flicker wildly or have turned black!!!! For example, both the iPhone wallpaper and the initial "slide to unlock" panel turn black and flicker, respectively... It makes no difference whether the photo came from the library or the camera. The problem is entirely averted (no lag, no blackness) if I do something like this:
//UIImage* image = (UIImage*)[info objectForKey:UIImagePickerControllerOriginalImage];
UIImage* image = [[UIImage alloc] initWithData:
[NSData dataWithContentsOfURL:
[NSURL URLWithString:
#"http://wild-facts.com/wp-content/uploads/2010/07/Diving_emperor_penguin.jpg"]]];
Thus I can't imagine the problem having to do with anything other than the UIImagePickerController. Note that I'm still creating and dismissing it-- I'm just not grabbing the image out of it.
At first I thought the image was simply being overreleased, and the disappearing black chunks were parts of memory being overwritten. However, changing the image's retain count makes no difference. Then I thought, maybe the image is too large and somehow not getting properly released when I dismiss the UIImageView! Yet downloading a several MB image from the internet will not replicate the error. Then I thought, maybe the UIImagePickerController is disposing of the image, regardless of retain count! But copying the image failed as well. Furthermore, how could any of these things effect views that exist as deep as the iOS level?! I've researched, experimented, and Googled and no one has encountered this problem except for me... yet I'm not doing particularly strange! Is this an Apple issue? Did I forget something obvious? I've scanned up and down the documentation and guides to no avail, but perhaps I missed something.
None of this has worked:
Incrementing the retain count
Using [image copy]
None of this has replicated the problem with the downloaded image:
Decrementing the retain count
Downloading an image of size greater than 1 MB with large dimensions
I'm using the latest Verizon iPhone with iOS 4.2.8 (base SDK "overriden" to 4.3, whatever that means). 4.2.8 is the latest possible one for Verizon, though 4.3 is available for iPhones using AT&T.
Here's the code in glorious detail. I'm not yet checking for device compatibility, but it shouldn't matter concerning this. Perhaps I forgot some setting with the UIImagePickerController?
Quick Overview: I display an action sheet, then based on the user's input, display the image picker. I save the image as a transformable attribute on a Core Data object (delivery) using a custom transformer. I later hand the image to a detail view controller to display to the user.
IGDeliveryVC.m (parts of it, anyways. It's a tableview displaying the delivery's added media)
- (void)refresh
{
[mediaDisplayArray release];
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"displayIndex" ascending:YES];
mediaDisplayArray = [[NSMutableArray alloc] initWithArray:
[delivery.deliveryMedia sortedArrayUsingDescriptors:
[NSArray arrayWithObject:sortDescriptor]]];
if (mediaDisplayArray == nil)
mediaDisplayArray = [[NSMutableArray alloc] init];
[self.tableView reloadData];
}
- (void)onAddMedia:(id)sender
{
#if TARGET_IPHONE_SIMULATOR
UIImage* image = [[UIImage alloc] initWithData:
[NSData dataWithContentsOfURL:
[NSURL URLWithString:
#"http://wild-facts.com/wp-content/uploads/2010/07/Diving_emperor_penguin.jpg"]]];
[delivery addImage:image];
[self refresh];
[image release];
return;
#endif
UIActionSheet *options = [[UIActionSheet alloc] initWithTitle:#"Add Media from..."
delegate:self
cancelButtonTitle:#"Cancel"
destructiveButtonTitle:nil
otherButtonTitles:#"Camera", #"Library", nil];
[options showFromToolbar:self.navigationController.toolbar];
[options release];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex != 0 && buttonIndex != 1)
return;
UIImagePickerController* picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = NO;
picker.mediaTypes = [NSArray arrayWithObjects:#"public.image",#"public.movie", nil];
switch (buttonIndex)
{
case 0:
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
break;
case 1:
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
break;
}
[self presentModalViewController:picker animated:YES];
}
- (void) imagePickerControllerDidCancel: (UIImagePickerController *) picker
{
[[picker parentViewController] dismissModalViewControllerAnimated:YES];
[picker release];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString* mediaType = (NSString*)[info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.image"])
{
UIImage* image = (UIImage*)[info objectForKey:UIImagePickerControllerOriginalImage];
//UIImage* image = [[UIImage alloc] initWithData:
// [NSData dataWithContentsOfURL:
// [NSURL URLWithString:
// #"http://wild-facts.com/wp-content/uploads/2010/07/Diving_emperor_penguin.jpg"]]];
[delivery addImage:image];
}
else if ([mediaType isEqualToString:#"public.movie"])
{
NSString* videoURL = (NSString*)[info objectForKey:UIImagePickerControllerMediaURL];
[delivery addVideo:videoURL];
}
else
{
NSLog(#"Error: imagePickerController returned with unexpected type %#", mediaType);
}
[[picker parentViewController] dismissModalViewControllerAnimated:YES];
[picker release];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
IGMedia* media = [mediaDisplayArray objectAtIndex:indexPath.row];
UIViewController* detailViewController =
[media isMemberOfClass:[IGMediaImage class]]
? [[IGMediaImageDetailVC alloc] initWithImage:((IGMediaImage*)media).image]
: nil;
if (detailViewController != nil)
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
}
IGMediaImageDetailVC.h (I use a xib :P )
#import <UIKit/UIKit.h>
#interface IGMediaImageDetailVC : UIViewController {
}
#property (nonatomic, retain) UIImage* image;
#property (nonatomic, retain) IBOutlet UIImageView* imageView;
- (id)initWithImage:(UIImage*)anImage;
#end
IGMediaImageDetailVC.m
#import "IGMediaImageDetailVC.h"
#implementation IGMediaImageDetailVC
#synthesize image;
#synthesize imageView;
- (id)initWithImage:(UIImage*)anImage
{
self = [super initWithNibName:#"IGMediaImageDetailVC" bundle:nil];
if (self)
{
self.image = anImage;
}
return self;
}
- (void)dealloc
{
[image release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.imageView.image = self.image;
}
- (void)viewDidUnload
{
[super viewDidUnload];
[imageView release];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
If there's anything I can do to make this post more legible, please let me know. I'll add things that don't work/replicate the problem to the appropriate list. Thanks for taking the time to read this!
I just figured out the problem, had to do with excessive memory use. Thanks goes to this amazing post: https://stackoverflow.com/questions/1282830/uiimagepickercontroller-uiimage-memory-and-more Basically, before ever displaying the image, I divide each dimension by 4, resulting in a total 1/16th of the memory I was using before. Here's the method I used (as per the awesome post):
+ (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize;
{
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
In the method call, I pass in CGSizeMake(image.size.width/4, image.size.height/4)
Hope this was helpful!

EXC_BAD_ACCESS error using ALAssetsLibrary assetForURL:resultBlock:failureBlock:

I'm trying to read the EXIF data from an image, selected by a user. I'm using the ALAssetLibrary for this. So far I've managed to get the reference URL needed for the assetForURL:resultBlock:failureBlock: method, but when I try to do anything with the reference URL i get a EXC_BAD_ACCESS error.
An NSLog of the URL, right before using it, results in the (correct, as far as i know) string:
assets-library://asset/asset.JPG?id=1000000003&ext=JPG
I've been trying to figure this out, but I seem to be hitting a dead end each time. I must admit I'm new to Objective-C in general, so please feel free to criticize my code accordingly.
Code (far from the complete classes, but i think it should be sufficient):
//Class_X.m
-(void)readExifDataFromSelectedImage:(NSURL *)imageRefURL
{
void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *) = ^(ALAsset *asset)
{
NSLog(#"Test:Succes");
};
ALAssetsLibrary *myAssetLib;
NSLog(#"%#",imageRefURL);
[myAssetLib assetForURL:imageRefURL
resultBlock:ALAssetsLibraryAssetForURLResultBlock
failureBlock:^(NSError *error){NSLog(#"test:Fail");}];
}
//Class_Y.m
//This also conforms to the UIImagePickerControllerDelegate And the NavigationControllerDelegate protocols:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
self.referenceURL = [info valueForKey:#"UIImagePickerControllerReferenceURL"];
NSString *mediaType = [info
objectForKey:UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:YES];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
UIImage *selectedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
imageView.image = selectedImage;
btnNoPicture.hidden = YES;
btnSelectPicture.hidden = YES;
btnTakePicture.hidden = YES;
imageView.hidden = NO;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Use this image?"
message:#"Are you sure you want to use this image?"
delegate:self
cancelButtonTitle:#"No"
otherButtonTitles:#"Yes", nil];
[alert show];
[alert release];
}
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)
{
//Do not use the selected image.
imageView.image = nil;
imageView.hidden = YES;
//Restart picking process
}
else
{
// I have an instance variable of type Class_X which i use
// throughout this class; let's call this variable "report".
// I also have the referenceURL stored as an instance variable.
[self.report readExifDataFromSelectedImage:self.referenceURL];
}
}
EXC_BAD_ACCESS is most often the result of an over-released object (dangling pointer). As the library operates asynchronously, your block is executed after the readExifDataFromSelectedImage: method has returned, so imageRefURL is probably already deallocated at this point. Try to retain the URL before requesting the asset and release it in the success and failure blocks.