Play recorded video using UIImagePickerController - iphone

I am creating an app which will record a video using UIImagePickerController and I am saving the recorded video in documents directory and trying to play back the video on click of USE (want to show the full first frame of recorded video along with play button in the middle like the native application of iPhone).
I am able to record the video and save it into document directory but unable to create the frame and playback.
I tried to move on new class where I can play the recorded video but gets crashed on click of USE button.
Here is my code
-(void)btnRecord_Press
{
BOOL canRecordVideo;
canRecordVideo = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
if (canRecordVideo)
{
UIImagePickerController *videoRecorder = [[UIImagePickerController alloc]init];
videoRecorder.sourceType = UIImagePickerControllerSourceTypeCamera;
videoRecorder.delegate=self;
videoRecorder.showsCameraControls = TRUE;
NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
NSArray *videoMediaTypesOnly = [mediaTypes filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(SELF CONTAINS %#)",#"movie"]];
BOOL movieOuputPossible = (videoMediaTypesOnly!=nil);
if (movieOuputPossible)
{
videoRecorder.mediaTypes = videoMediaTypesOnly;
[self presentViewController:videoRecorder animated:YES completion:nil];
}
}
}
-(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];
[self dismissViewControllerAnimated:NO completion:nil];
PlayMovie *play = [[PlayMovie alloc]initWithNibName:#"PlayMovie" bundle:Nil];
[self.navigationController pushViewController:play animated:YES];
}
Any help would be appreciable.
Thanks

I did this using this code.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
[self dismissViewControllerAnimated:NO completion:nil];
[self Play];
}
-(void)Play
{
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];
player = [[MPMoviePlayerController alloc]initWithContentURL:videoURL];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(btnDone_Press) name:MPMoviePlayerWillExitFullscreenNotification object:nil];
self._player.shouldAutoplay = NO;
UIImage *thumbnail = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
screenSize = [[UIScreen mainScreen]bounds].size;
if (screenSize.height >480.0f)
{
player.view.frame = CGRectMake(0, 0, 320, 548);
}
else
{
player.view.frame = CGRectMake(0, 0, 320, 460);
}
}
[self.view addSubview:player.view];
self._player.scalingMode = MPMovieScalingModeAspectFit;
self._player.fullscreen = YES;
[self._player play];
}

Related

How to record a video clip in ipad app and store it in documents folder

I have training app i want that when user click recordVideo button camera should launch to record video, is there any way to do this in ipad app.I have done audio recording already i need to do video recording.
//for video..
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/Mediaplayer.h>
#import <CoreMedia/CoreMedia.h>
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
NSArray *mediaTypes = [NSArray arrayWithObject:(NSString*)kUTTypeMovie];
picker.mediaTypes = mediaTypes ;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo ;
[self presentModalViewController:picker animated:NO];
[picker release];
}
else
{
UIAlertView *alt=[[UIAlertView alloc]initWithTitle:#"Error" message:#" Camera Facility is not available with this Device" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alt show];
[alt release];
}
for saving into Document folder & it also save in photo Library
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
//for video
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"video url-%#",videoURL);
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSString * videoName = [NSString stringWithFormat:#"student_%d_%d.mp4",stud_id,imgVidID];
videoPath = [documentsDirectory stringByAppendingPathComponent:videoName];
NSLog(#"video path-%#",videoPath);
[videoData writeToFile:videoPath atomically:YES];
NSString *sourcePath = [[info objectForKey:#"UIImagePickerControllerMediaURL"]relativePath];
UISaveVideoAtPathToSavedPhotosAlbum(sourcePath,nil,nil,nil);
}
Try this ::
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
[self dismissViewControllerAnimated:NO completion:nil];
NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
if ([type isEqualToString:(NSString *)kUTTypeVideo] || [type isEqualToString:(NSString *)kUTTypeMovie])
{
videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"found a video");
// Code To give Name to video and store to DocumentDirectory //
videoData = [[NSData dataWithContentsOfURL:videoURL] retain];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:#"dd-MM-yyyy||HH:mm:SS"];
NSDate *now = [[[NSDate alloc] init] autorelease];
theDate = [dateFormat stringFromDate:now];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Default Album"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
NSString *videopath= [[[NSString alloc] initWithString:[NSString stringWithFormat:#"%#/%#.mov",documentsDirectory,theDate]] autorelease];
BOOL success = [videoData writeToFile:videopath atomically:NO];
NSLog(#"Successs:::: %#", success ? #"YES" : #"NO");
NSLog(#"video path --> %#",videopath);
}
}
Hopefully, It'll help you.
Thanks.
Just try it :
-(void) imagePickerController: (UIImagePickerController *) picker didFinishPickingMediaWithInfo: (NSDictionary *) info
{
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:NO];
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) {
[AJNotificationView showNoticeInView:self.view type:AJNotificationTypeRed title:#"Video Saving Failed" linedBackground:AJLinedBackgroundTypeAnimated hideAfter:1.0];
}
else{
NSURL *videoURl = [NSURL fileURLWithPath:videoPath];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURl options:nil];
AVAssetImageGenerator *generate = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generate.appliesPreferredTrackTransform = YES;
NSError *err = NULL;
CMTime time = CMTimeMake(1, 60);
CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:NULL error:&err];
self.strUploadVideoURL = videoPath;
[imgPhoto setImage:[[[UIImage alloc] initWithCGImage:imgRef] autorelease]];
intWhenPushView = 2;
btnShare.enabled = YES;
btnFacebookShare.enabled = YES;
CGImageRelease(imgRef);
[generate release];
[asset release];
}
}

let user change background on 4 different imageviews xcode

im trying to make an app that has 4 ImageViews and I want to allow the user to change the background on the different ImageViews by pressing an UIButton below each ImageView. I have written a code for this from a tutorial showing to do this with just one ImageView. I just copied and pasted 4 times for each button and changed some variables. But when I run it only the first ImageView changes its picture even if I press UIButton for 2nd, 3rd or 4th ImageView. here the code:
#import "ViewController.h"
#interface ViewController ()
{
UIImagePickerController *imagePickerController;
UIImagePickerController *imagePickerController2;
UIImagePickerController *imagePickerController3;
UIImagePickerController *imagePickerController4;
}
#end
#implementation ViewController
#synthesize firstImageView, secondImageView, thirdImageView, fourthImageView;
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (IBAction)firstChangeButton:(id)sender
{
imagePickerController = [[UIImagePickerController alloc]init];
[imagePickerController setDelegate:self];
[imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:imagePickerController animated:YES completion:nil];
}
- (IBAction)secondChangeButton:(id)sender
{
imagePickerController2 = [[UIImagePickerController alloc]init];
[imagePickerController2 setDelegate:self];
[imagePickerController2 setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:imagePickerController2 animated:YES completion:nil];
}
- (IBAction)thirdChangeButton:(id)sender
{
imagePickerController3 = [[UIImagePickerController alloc]init];
[imagePickerController3 setDelegate:self];
[imagePickerController3 setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:imagePickerController3 animated:YES completion:nil];
}
- (IBAction)fourthChangeButton:(id)sender
{
imagePickerController4 = [[UIImagePickerController alloc]init];
[imagePickerController4 setDelegate:self];
[imagePickerController4 setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:imagePickerController4 animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image1 = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *data = UIImagePNGRepresentation(image1);
NSString *myGrabbedImage = #"myGrabbedImage.png";
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [path objectAtIndex:0];
NSString *fullPathToFile = [documentDirectory stringByAppendingPathComponent:myGrabbedImage];
[data writeToFile:fullPathToFile atomically:YES];
[[self firstImageView]setImage:image1];
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController2:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info2
{
UIImage *image2 = [info2 objectForKey:UIImagePickerControllerOriginalImage];
NSData *data2 = UIImagePNGRepresentation(image2);
NSString *myGrabbedImage2 = #"myGrabbedImage2.png";
NSArray *path2 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory2 = [path2 objectAtIndex:0];
NSString *fullPathToFile2 = [documentDirectory2 stringByAppendingPathComponent:myGrabbedImage2];
[data2 writeToFile:fullPathToFile2 atomically:YES];
[[self secondImageView]setImage:image2];
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController3:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info3
{
UIImage *image3 = [info3 objectForKey:UIImagePickerControllerOriginalImage];
NSData *data3 = UIImagePNGRepresentation(image3);
NSString *myGrabbedImage3 = #"myGrabbedImage3.png";
NSArray *path3 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory3 = [path3 objectAtIndex:0];
NSString *fullPathToFile3 = [documentDirectory3 stringByAppendingPathComponent:myGrabbedImage3];
[data3 writeToFile:fullPathToFile3 atomically:YES];
[[self thirdImageView]setImage:image3];
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController4:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info4
{
UIImage *image4 = [info4 objectForKey:UIImagePickerControllerOriginalImage];
NSData *data4 = UIImagePNGRepresentation(image4);
NSString *myGrabbedImage4 = #"myGrabbedImage4.png";
NSArray *path4 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory4 = [path4 objectAtIndex:0];
NSString *fullPathToFile4 = [documentDirectory4 stringByAppendingPathComponent:myGrabbedImage4];
[data4 writeToFile:fullPathToFile4 atomically:YES];
[[self fourthImageView]setImage:image4];
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
How should i apply it for all 4 ImageViews?
Thanks in advance!
The problem is that all image pickers will call the same delegate method:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
When you set the delegate for the image picker controller like so:
[imagePickerController setDelegate:self];
You basically tell the image picker controller that self will be able to respond to the image picker delegate methods.
As you can see in the UIImagePickerControlDelegate, there's no such thing as:
– imagePickerController2:didFinishPickingMediaWithInfo:
and so on.
As a start, I would suggest rewriting your delegate method like this:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image1 = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *data = UIImagePNGRepresentation(image1);
NSString *myGrabbedImage = #"myGrabbedImage.png";
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [path objectAtIndex:0];
NSString *fullPathToFile = [documentDirectory stringByAppendingPathComponent:myGrabbedImage];
[data writeToFile:fullPathToFile atomically:YES];
if (picker == imagePickerController) {
[[self firstImageView]setImage:image1];
} else if (picker == imagePickerController2) {
[[self secondImageView]setImage:image1];
} else if (picker == imagePickerController3) {
[[self thirdImageView]setImage:image1];
} else {
[[self fourthImageView]setImage:image1];
}
[self dismissViewControllerAnimated:YES completion:nil];
}
This way, all image picker images will be handled by the same method, thus reducing the amount of code.

UIImagePickerController - Save and Retrieve photo from Apps Document Directory

This is driving me crazy!
I'm successfully saving a photo to my applications document directory from both the camera and if I choose an existing one from the camera roll. The code to do this is as follows. Note I know this part is working because in the simulator I can browse to the apps Documents folder and see the file being saved.
Example "save" code:
//Note: code above snipped to keep this part of the question short
case 1:
{
// select from library
NSLog(#"select from camera roll");
if([util_ isPhotoLibraryAvailable])
{
UIImagePickerController *controller = [[UIImagePickerController alloc] init];
controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
if([util_ canUserPickPhotosFromPhotoLibrary])
{
[mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
}
controller.mediaTypes = mediaTypes;
controller.delegate = self;
controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:controller animated:YES];
}
} break;
//code below snipped out
And once the image is taken or selected:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSLog(#"picker returned successfully");
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if([mediaType isEqualToString:(__bridge NSString *)kUTTypeImage])
{
UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
UIImage *resizedImage = [util_ createThumbnailForImage:originalImage thumbnailSize:[util_ determineIPhoneScreenSize]];
NSData *imageData = UIImagePNGRepresentation(resizedImage);
NSString* imageName = #"MyImage.png";
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
[imageData writeToFile:fullPathToFile atomically:NO];
NSLog(#"fullPathToFile %#", fullPathToFile);
// this outputs the following path in the debugger
// fullPathToFile /Users/me/Library/Application Support/iPhone Simulator/5.0/Applications/47B01A4C-C54F-45C4-91A3-C4D7FF9F95CA/Documents/MyImage.png
// rest snipped out - at this point I see the image in the simulators/app/Documents directory
Now - the part that is NOT working (fetching and displaying the photo):
// code above snipped out (we're in tableView:cellForRowAtIndexPath)
imageButton_ = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 200, 200)];
NSString* imageName = [contentArray_ objectAtIndex:indexPath.row];
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
SString* documentsDirectory = [paths objectAtIndex:0];
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
UIImage *image = [UIImage imageNamed:fullPathToFile];
[imageButton_ setImage:image forState:UIControlStateNormal];
[cell addSubview:imageButton_];
NSLog(#"fullPathToFile: %#", fullPathToFile);
// this outputs the following path in the debugger
// fullPathToFile: /Users/me/Library/Application Support/iPhone Simulator/5.0/Applications/47B01A4C-C54F-45C4-91A3-C4D7FF9F95CA/Documents/MyImage.png
return cell;
}
So, I get an empty button with no image displayed in the cell. I have also substituted the button for a UIImageView and still no luck...
Your problem is here:
UIImage *image = [UIImage imageNamed:fullPathToFile];
UIImage imageNamed: is only for images in the bundle. It doesn't work for images in the documents directory.
Try imageWithContentsOfFile: instead.

How to Display photos from NSDocumentDirectory

I'm developing this application on an iPad.
These codes for a 'Browse' button allows the user to view the photos from the iPad's gallery.
Code:
- (IBAction) BrowsePhoto:(id)sender
{
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.delegate = self;
imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:imagePickerController];
[popover setPopoverContentSize:CGSizeMake(320,320)];
[popover presentPopoverFromRect:CGRectMake(200,200,-100,-100) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
self.popoverController = popover;
[imagePickerController release];
}
When a photo is selected, it will be stored into the application using NSDocumentDirectory.
Code:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)selectedImage editingInfo:(NSDictionary *)editingInfo
{
[self.popoverController dismissPopoverAnimated:YES];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:#"SavedImage.png"];
UIImage *image = imageView.image;
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
}
Now i have to include a 'Display' button on the first screen.
When tapped on the button, it will show a new view (modal view controller) and displays all the photos in thumbnails/tableview from the NSDocumentDirectory.
When a photo is selected, it will be deleted from the NSDocumentDirectory.
How can i do this?
To Delete any file in NSDocumentDirectory in iPhone, U can use this code,
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES );
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath2 = [NSString stringWithFormat:#"%#/%#", docDirectory,#"SavedImage.png"];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL exist =[fileManager fileExistsAtPath:filePath2];
if(exist)
[fileManager removeItemAtPath:filePath2 error:NULL];

Trying to save images in ipad app bundle from photo library

-(IBAction)saveImage{
NSMutableArray *dictWords= [[NSMutableArray alloc]initWithObjects:#"TIGER",#"CAT", #"ROSE", #"ELEPHANT",#"MOUSE IS LOOKING FOR THE CHEESE",#"KITE",#"CAR",#"AEROPLANE",#"MANGO",#"FRUITS ARE FALLING FROM THE TREE",#"MOUNTAIN",#"BIRDS ARE FLYING",#"IGLOO",#"THIS HOUSE IS BUILT OF WOODS",#"BANANA",#"RAINBOW",#"TRAIN",#"DADDY DRINKS JUICE",#"UMBRELLA",#"GOAT",#"CAT JUMPS HIGH",#"DOG RUNS FAST",#"BUS",#"GIRL IS CRYING",#"STARS",#"DOLPHIN",#"BOYS ARE PLAYING FOOTBALL",#"GLASS IS FULL OF WATER",#"SHIP",#"SNOWFALL",#"GHOST",#"RABBIT",#"WATERMELON",#"SPIDERMAN",#"DINOSAUR",#"MICKEY MOUSE",#"MONKEY IS SITTING ON A TREE",#"PEACOCK",#"LIGHTNING",#"HEN LAYS EGGS",nil];
NSString *path=[[NSBundle mainBundle] pathForResource:[youSaid text] ofType:#"png" inDirectory:#"Image"];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
for (int i=0 ; i<[assets count]; i++) {
if (i<[dictWords count]) {
[dict setObject:[[[assets objectAtIndex:i] defaultRepresentation] url] forKey:[NSString stringWithFormat:#"%#",[dictWords objectAtIndex:i]]];
NSLog(#"diccount:%d",[dict count]);
}
}
NSURL *imageurl = [dict objectForKey:[youSaid text]];
//NSLog(#"text:%#",[youSaid text]);
//Getting asset from url
typedef void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *asset);
typedef void (^ALAssetsLibraryAccessFailureBlock)(NSError *error);
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
ALAssetRepresentation *rep = [myasset defaultRepresentation];
CGImageRef iref = [rep fullResolutionImage];
//Setting asset image to image view according to the image url
[imageview setImage:[UIImage imageWithCGImage:iref]];
youSaid.text = [NSString stringWithFormat:#"%#",imageurl];
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
NSLog(#"Error, cant get image - %#",[myerror localizedDescription]);
};
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:imageurl resultBlock:resultblock failureBlock:failureblock];
UIImage *image=[[UIImage alloc]initWithContentsOfFile:path];
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", youSaid.text]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the image
NSLog(#"image saved");
}
#end
This is the following code i wrote but i am not able to save images.i am only able to sane an image known as NULL.png .please suggest the changes to save all the pics in my library to bundle.
Thanks,
Christy
Sample Code
- (void) openPhotoLibrary {
NSLog(#"openPhotolibrary");
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
if (self.picker != nil) {
NSLog(#"releasing self.picker...");
[self.picker release];
}
self.picker = [[UIImagePickerController alloc] init];
self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//self.picker.allowsImageEditing = YES;
[self.picker presentModalViewController:self.picker animated:YES];
self.picker.delegate = self;
[[[CCDirector sharedDirector] openGLView] addSubview:self.picker.view];
}
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)currentPicker {
NSLog(#"imagePickerControllerDidCancel");
// hide the self.picker if user cancels picking an image.
[currentPicker dismissModalViewControllerAnimated:YES];
self.picker.view.hidden = YES;
[self.picker.view removeFromSuperview];
}
- (void)imagePickerController:(UIImagePickerController *)currentPicker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
[self saveImage:image withImageName:#"myPhoto"];
}
//saving an image
- (void)saveImage:(UIImage*)image withImageName:(NSString*)imageName {
NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", imageName]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)
NSLog(#"image saved");
}
This code its working for me try it may be its helps you
-(IBAction)PhotoLibraryButtonClicked:(id)sender{
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:imagePicker animated:YES];
}
else{
[self displaysorceError];
}
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
//[self.popoverrcontroller dismissPopoverAnimated:true];
//[popoverrcontroller release];
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:YES];
if([mediaType isEqualToString:(NSString *)kUTTypeImage]){
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
// UIImage *rote = [image rotateInDegrees:219.0f];
img.image = image;
if(newMedia)
UIImageWriteToSavedPhotosAlbum(image, nil,nil, nil);
}else if([mediaType isEqualToString:(NSString *)kUTTypeImage]){
//not available vidio
}
}
-(IBAction)saveImageIn:(id)sender{
NSData *imageData = UIImagePNGRepresentation(img.image);
NSFileManager *fileMan = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#" %d.png",img.image]];
[fileMan createFileAtPath:fullPathToFile contents:imageData attributes:nil];
UIAlertView *alt = [[UIAlertView alloc]
initWithTitle:#"Thank You"
message:#"Image Save In Directory"
delegate:nil cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alt show];
[alt release];
}
thank you..:)Neet