writeImageToSavedPhotosAlbum:metadata:completionBlock: - iphone

I use the method writeImageToSavedPhotosAlbum:metadata:completionBlock: save taken picture to photo album,code is:
-(void)savePhotoToAlbum{
CGImageRef imageRef=[imageView image].CGImage;
NSDictionary *currentDic=[self getLocation];
NSDictionary *metadata=[NSDictionary dictionaryWithDictionary:currentDic];
ALAssetsLibrary *library=[[ALAssetsLibrary alloc] init];
[library writeImageToSavedPhotosAlbum:imageRef metadata:metadata completionBlock:^(NSURL *assetURL,NSError *error){
if(error == nil)
{
UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:nil message:#"Save success!" delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
else
{
UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:nil message:#"Save failure!" delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
}];
[library release];
}
.The method getLocation that is get user's current location!That can save success!Then I want to pick taken picture from photo album use UIImagePickerController! Code is :
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{ if([picker sourceType]==UIImagePickerControllerSourceTypeSavedPhotosAlbum)//picker image delegate
{
NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
if([mediaType isEqualToString:#"public.image"])
{
NSDictionary *metadata=[info objectForKey:UIImagePickerControllerMediaMetadata];
NSLog(#"%#",metadata);
}
}
}
Then log the metadata is null.That's why? And how do I get the metadata info which I saved?Thanks!

The metadata of the image will be available only if the sourceType is UIImagePickerControllerSourceTypeCamera.
See Ref. Look at the last paragraph in that page.

You can take log of metadata with AssetsLibrary framework:
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
...
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString*)kUTTypeImage]) {
NSURL *url = [info objectForKey:UIImagePickerControllerReferenceURL];
if (url) {
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset) {
CLLocation *location = [myasset valueForProperty:ALAssetPropertyLocation];
NSLog(#"\n\n\n____________________________\n");
NSLog(#"ORIENTATION: %#\n",[myasset valueForProperty:ALAssetPropertyOrientation]);
NSLog(#"LOCATION: %#\n",[myasset valueForProperty:ALAssetPropertyLocation]);
NSLog(#"DATE: %#\n",[myasset valueForProperty:ALAssetPropertyDate]);
NSLog(#"Duration: %#\n",[myasset valueForProperty:ALAssetPropertyDuration]);
NSLog(#"TYPE: %#\n",[myasset valueForProperty:ALAssetPropertyType]);
NSLog(#"\n____________________________\n\n\n");
//take coordinates only
CLLocationCoordinate2D coordinate = [location coordinate];
strCoord = [NSString stringWithFormat:#"long: %f; lat: %f;", coordinate.latitude, coordinate.longitude];
NSLog(#"%#", strCoord);
// location contains lat/long, timestamp, etc
// extracting the image is more tricky and 5.x beta ALAssetRepresentation has bugs!
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror) {
NSLog(#"cant get image - %#", [myerror localizedDescription]);
};
ALAssetsLibrary *assetsLib = [[ALAssetsLibrary alloc] init];
[assetsLib assetForURL:url resultBlock:resultblock failureBlock:failureblock];
}
}
...
}

Related

image getting saved in simulator gallery but not in iphone gallery

Trying to save the image in iphone gallery with following code below, but working fine in simulator, not in iphone.
-(void)saveTkt
{
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
CGRect rect = [keyWindow bounds];
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[keyWindow.layer renderInContext:context];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData * data = UIImagePNGRepresentation(img);
[data writeToFile:#"f.png" atomically:YES];
UIImageWriteToSavedPhotosAlbum(img, self, #selector(thisImage:hasBeenSavedInPhotoAlbumWithError:usingContextInfo:), nil);
}
edited code
-(void)saveTkt
{
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
CGRect rect = [keyWindow bounds];
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[keyWindow.layer renderInContext:context];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData * data = UIImagePNGRepresentation(img);
[data writeToFile:#"f.png" atomically:YES];
ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];
if (status != ALAuthorizationStatusAuthorized) {
//show alert for asking the user to give permission
}
//UIImageWriteToSavedPhotosAlbum(img, self, #selector(thisImage:hasBeenSavedInPhotoAlbumWithError:usingContextInfo:), nil);
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeImageToSavedPhotosAlbum:[img CGImage] orientation:(ALAssetOrientation)[img imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
if (error) {
// TODO: error handling
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"error" message:[error localizedDescription] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
} else {
// TODO: success handling
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"alert" message:#"Saved suceesfully in photos album." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}];
ALAssetsLibraryGroupsEnumerationResultsBlock assetGroupEnumerator =
^(ALAssetsGroup *assetGroup, BOOL *stop) {
if (assetGroup != nil) {
// do somthing
}
};
ALAssetsLibraryAccessFailureBlock assetFailureBlock = ^(NSError *error) {
NSLog(#"Error enumerating photos: %#",[error description]);
};
NSUInteger groupTypes = ALAssetsGroupAll;
[library enumerateGroupsWithTypes:groupTypes usingBlock:assetGroupEnumerator failureBlock:assetFailureBlock];
}
Add Framework assetsLibrary
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
if (error) {
// TODO: error handling
} else {
// TODO: success handling
}
}];
[library release];
Apple's documentation say that the completion handler must conform to this:
- (void) image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo;
And there's an error parameter passed along, which you should print out to see what the actual true error is.
For example:
- (void) image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
if(error != NULL)
{
NSLog( #"error while saving image is %#", [error localizedDescription]);
}
}
I think you should try with NSData first if you need It, or you can simply do that without NSData
NSData *dataImage = UIImageJPEGRepresentation(file,1);
UIImageView *img;
img.image = [[UIImage alloc] initWithData:dataImage];
UIImageWriteToSavedPhotosAlbum( [[UIImage alloc] initWithData:dataImage], nil, nil, nil);
Hope ,it will work

What is the correct way to write the video in asset library and then get their attributes

I am writing video in Asset library using
[library writeVideoAtPathToSavedPhotosAlbum:movieUrl completionBlock:^(NSURL *assetURL, NSError *error) block
gives the url before the video completely write to the asset library. And when i enumerate the library inside the block to get the attributes of video i did not get any video against the url given by above block.
If i manually re-enumerate the asset library 3 or 4 times with the same url i get the video attribures.
This problem mostly occurs when i make video of duration greater than 5 min
My code is:
library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:movieUrl completionBlock:^(NSURL *assetURL, NSError *error)
{
savedAssetURL = assetURL;
[self assetsEmumeration:assetURL];
NSLog(#"asset url %#",assetURL);
if(error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Failed" message:[error localizedDescription] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:Nil];
[alertView show];
}
}];
-(void) assetsEmumeration:(NSURL *)_url
{
NSLog(#"assets enumeration ");
ALAssetsLibrary *al;
void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop)
{
[group setAssetsFilter:[ALAssetsFilter allVideos]] ;
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset)
{
ALAssetRepresentation *representation = [asset defaultRepresentation];
NSURL *url = [representation url];
if([[url absoluteString] isEqualToString:[_url absoluteString]])
{
found = TRUE;
NSDictionary *asset_options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
AVAsset *avAsset = [[AVURLAsset alloc] initWithURL:url options:asset_options];
Float64 dur = CMTimeGetSeconds(avAsset.duration);
NSString *fileName = [representation filename];
appDelegate.videoLength = [NSString stringWithFormat:#"%f seconds",dur];
appDelegate.videoSize = [NSString stringWithFormat:#"%lld bytes",[representation size]];
appDelegate.originalFileName = [NSString stringWithFormat:#"%#",fileName];
[MBProgressHUD hideHUDForView:self.view animated:YES];
ExtraInfoViewController *extraInfoViewObj = [[ExtraInfoViewController alloc] init];
[self.navigationController pushViewController:extraInfoViewObj animated:YES];
NSLog(#"duration:%f,fileName:%#",dur,fileName);
}
else
{
found = FALSE;
}
}
}];
if(found == FALSE)
{
NSLog(#"video not found");
}
};
void (^assetFailureBlock)(NSError *) = ^(NSError *error)
{
NSLog(#"failure");
if(ALAssetsLibraryAccessGloballyDeniedError)
{
UIAlertView *alerview = [[UIAlertView alloc] initWithTitle:#"Denied" message:#"Failed to get the meta data. Access to assets library is denied" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:Nil];
[alerview show];
}
};
al=[RecordVideoViewController defaultAssetsLibrary];
[al enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:assetGroupEnumerator failureBlock:assetFailureBlock];
}
// find out alAsset for that url and then do whatever you want with alAsset.
library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:movieUrl completionBlock:^(NSURL *assetURL, NSError *error)
{
savedAssetURL = assetURL;
NSLog(#"asset url %#",assetURL);
if(error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Failed" message:[error localizedDescription] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:Nil];
[alertView show];
}
else
{
[library assetForURL:assetURL
resultBlock:^(ALAsset* alAsset) {
// do whatever you want with alAsset
}];
}
}];

How to save a video using code in objective c?

I have captured a video using objective c,however I am not able to save it in the iphone photos library.I dont want to use the AlAssets library,I want to use the image picker only.I have seen a lot of methods on stack overflow and other sites but they either use storage location path(which is not mentioned what it is) or they dont work.
This is my piece of code.
-(IBAction)Onclick:(id)sender
{
UIImagePickerController *imagePicker = [[UIImagePickerController
alloc] init];
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = [NSArray arrayWithObject:(NSString *)
kUTTypeMovie];
imagePicker.delegate = self;
//UISaveVideoAtPath
imagePicker.allowsImageEditing = NO;
[self.view addSubview:imagePicker.view];
[imagePicker viewWillAppear:YES];
CGRect overlayFrame = CGRectMake(0, 380, 320, 44);
//UILabel *lbl=[[UILabel alloc]init];
UIView *baseView = [[[UIView alloc] init] autorelease];
baseView.backgroundColor =[UIColor greenColor];
//lbl.text=#"dfgfdgfd";
baseView.frame=overlayFrame;
//view.delegate = self;
//view.picker = picker;
//[view customize];
imagePicker.cameraOverlayView = baseView;
[self presentModalViewController:imagePicker animated:YES];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.image"]){
UIImage *picture = [info objectForKey:UIImagePickerControllerOriginalImage];
UIImageWriteToSavedPhotosAlbum(picture, nil, nil, nil);
}
else if ([mediaType isEqualToString:#"public.movie"]){
NSURL *url = [[[info objectForKey:UIImagePickerControllerMediaURL] copy] autorelease];
// ALAssetsLibrary* library = [[[ALAssetsLibrary alloc] init] autorelease];
// [library writeVideoAtPathToSavedPhotosAlbum:url
// completionBlock:^(NSURL *assetURL, NSError *error){/*notify of completion*/}];
UISaveVideoAtPathToSavedPhotosAlbum(url, nil, nil, nil);
}
[self dismissModalViewControllerAnimated:YES];
}
Try this:
- (void) imagePickerController: (UIImagePickerController *) picker
didFinishPickingMediaWithInfo: (NSDictionary *) info
{
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
[self dismissViewControllerAnimated:YES completion:nil];
// Handle a movie capture
if (CFStringCompare (( CFStringRef) mediaType, kUTTypeMovie, 0)
== kCFCompareEqualTo)
{
NSString *moviePath = [[info objectForKey:
UIImagePickerControllerMediaURL] path];
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum (moviePath))
{
UISaveVideoAtPathToSavedPhotosAlbum (moviePath,self, #selector(video:didFinishSavingWithError:contextInfo:), nil);
}
}
}
}
- (void)video:(NSString*)videoPath didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
if (error)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Photo/Video Saving Failed" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil, nil];
[alert show];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Photo/Video Saved" message:#"Saved To Photo Album" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
}
Hope it helps you.
Try this:
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:videoURL completionBlock:^(NSURL *assetURL, NSError *error){
/*notify of completion*/
NSLog(#"AssetURL: %#",assetURL);
NSLog(#"Error: %#",error);
if (!error) {
//video saved
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:error.domain delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
}];

Want to get my captured video back

I have created a camera using AVFoundation, now i want my video back so i can upload it on my server how can i do that ?
I am using MKNetworkKit for upload video on server.
I am getting output like this:
file://localhost/private/var/mobile/Applications/4B2E02E5-3EE2-493E-8ECF-4B1DA29B9387/tmp/output.mov
Guys I have figured out it by some help here is code for that.
- (void) captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)anOutputFileURL
fromConnections:(NSArray *)connections
error:(NSError *)error
{
videodata = [NSData dataWithContentsOfURL:outputFileURL];
//NSLog(#"output file url is :%#",anOutputFileURL);
NSLog(#"output video data size is:%d", videodata.length);
if ([[self delegate] respondsToSelector:#selector(recorder:recordingDidFinishToOutputFileURL:error:)]) {
[[self delegate] recorder:self recordingDidFinishToOutputFileURL:anOutputFileURL error:error];
}
//NSLog(#"captureOutput is: %#",captureOutput);
// NSLog(#"anOutputFileURL is: %#",anOutputFileURL);
//videoPath = [NSString stringWithContentsOfURL:anOutputFileURL encoding:NSUTF8StringEncoding error:nil];
//videoPath = [anOutputFileURL absoluteString];
//videoURL = anOutputFileURL;
// videodata = captureOutput;
// NSLog(#"video path is: %#",videodata);
UIAlertView *message = [[UIAlertView alloc] initWithTitle:nil
message:#"Do you want to upload this content to the yes stream network ?"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Yes",#"No",nil];
[message show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Yes"])
{
NSLog(#"Yes was selected.");
self.flUploadEngine = [[fileUploadEngine alloc] initWithHostName:#"manektech.net" customHeaderFields:nil];
NSMutableDictionary *postParams = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"testApp", #"appID",
nil];
self.flOperation = [self.flUploadEngine postDataToServer:postParams path:#"/dilipvideotest/savefile.php"];
[self.flOperation addData:videodata forKey:#"uploadfile" mimeType:#"video/mov" fileName:#"output.mov" ];
[self.flOperation onCompletion:^(MKNetworkOperation *operation) {
NSLog(#"response string is : %#", [operation responseString]);
/*
This is where you handle a successful 200 response
*/
}
onError:^(NSError *error) {
NSLog(#"error : %#", error);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles:nil];
[alert show];
}];
[self.flUploadEngine enqueueOperation:self.flOperation ];
}
else if([title isEqualToString:#"No"])
{
NSLog(#"No was selected.");
//[self readMovie:outputFileURL];
}
}

how to prevent saving picture from camera roll again

May be this question is too easy or I did not know how easy it will be.
I have an actionsheet to allow the user to choose how if they want to take a photo or select from camera.
The app will save user taken photo regardless is selected from camera roll or taken from camera. Am I missing something?
Thanks for reading my question.
#pragma mark - photo select
-(IBAction)showCameraAction:(id)sender
{
if(![UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeCamera])
{
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:#""
delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil
otherButtonTitles:#"Choose Photo From Library", nil];
actionSheet.actionSheetStyle = UIActionSheetStyleAutomatic;
actionSheet.tag =1;
[actionSheet showInView:[self.view superview]];
}
else
{
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:#""
delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil
otherButtonTitles:#"Take Photo With Camera", #"Choose Photo From Library", nil];
actionSheet.actionSheetStyle = UIActionSheetStyleAutomatic;
actionSheet.tag =1;
[actionSheet showInView:[self.view superview]];
}
}
- (void)getPhotoFromSource:(UIImagePickerControllerSourceType)sourceType;
{
//NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:sourceType];
if ([UIImagePickerController isSourceTypeAvailable:sourceType])
{
//NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:sourceType];
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
//picker.mediaTypes = mediaTypes;
picker.delegate = self;
//picker.allowsEditing = YES;
picker.sourceType = sourceType;
[self presentModalViewController:picker animated:YES];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error accessing media" message:#"Device doesn't support media source" delegate:nil cancelButtonTitle:#"Drat" otherButtonTitles:nil, nil];
[alert show];
}
}
#pragma mark UIImagePickerController delegate methods
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
self.lastChosenMediaType = [info objectForKey:UIImagePickerControllerOriginalImage];
imageFrame=fImageView.frame;
//UIImage *chosenImage = [info objectForKey:UIImagePickerControllerEditedImage];
UIImage *orginalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
UIImage *shrunkenImage = shrinkImage(orginalImage,imageFrame.size);
self.fImage = shrunkenImage;
fImageView.image = frogImage;
//answer fix, to prevent saving picture from cameraroll again.
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
{
UIImageWriteToSavedPhotosAlbum(orginalImage, self, #selector(imageSavedToPhotosAlbum: didFinishSavingWithError: contextInfo:), nil);
}
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
//NSString *message;
//NSString *title;
// if (!error) {
// title = NSLocalizedString(#"SaveSuccessTitle", #"");
// message = NSLocalizedString(#"SaveSuccessMessage", #"");
// } else {
// title = NSLocalizedString(#"SaveFailedTitle", #"");
// message = [error description];
// }
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
// message:message
// delegate:nil
// cancelButtonTitle:NSLocalizedString(#"ButtonOK", #"")
// otherButtonTitles:nil];
// [alert show];
}
Try this code.. Its working properly from my side.
- (IBAction) uploadPhoto:(id)sender
{
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:#""
delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil
otherButtonTitles:#"Use Photo from Library", #"Take Photo with Camera", nil];
actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
actionSheetAction = ActionSheetToSelectTypeOfSource;
[actionSheet showInView:self.view];
[actionSheet release];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
UIImagePickerControllerSourceType sourceType;
if (buttonIndex == 0) {
sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
} else if(buttonIndex == 1) {
sourceType = UIImagePickerControllerSourceTypeCamera;
}else {
// Cancel
break;
}
if([UIImagePickerController isSourceTypeAvailable:sourceType]) {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.sourceType = sourceType;
picker.delegate = self;
if (sourceType == UIImagePickerControllerSourceTypeCamera) {
picker.cameraFlashMode = UIImagePickerControllerCameraFlashModeOn;
}
picker.allowsImageEditing = NO;
[self presentModalViewController:picker animated:YES];
[picker release];
}
}
#pragma mark -
#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [paths objectAtIndex:0];
NSString *imgPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"image1.png"]];
//COnvert it to NSData before saving and then save it
NSData *imgData = UIImagePNGRepresentation(image);
[imgData writeToFile:imgPath atomically:YES];
[self dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[self dismissModalViewControllerAnimated:YES];
}
you need to implement UIImagePickerControllerDelegate
Check this function
(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{}
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.image"]){
UIImage *editedImage = [info objectForKey:UIImagePickerControllerEditedImage];
}
Now use this UIImage
To save this Image You have to specify a path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"photo.png"]];
//COnvert it to NSData before saving and then save it
NSData *webData = UIImagePNGRepresentation(editedImage);
[webData writeToFile:imagePath atomically:YES];