I’m developing this application on an iPad.
It has a function that allows user to store images from the iPad’s photo gallery into the application via NSDocumentDirectory.
There’s a browse button, confirm button and one imageview in the first screen.
The browse button will display the photos from the iPad’s photo gallery and allows the user to select a photo.
The confirm button will store the selected photo into NSDocumentDirectory.
Browse button:
- (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];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)selectedImage editingInfo:(NSDictionary *)editingInfo
{
[self.popoverController dismissPopoverAnimated:YES];
imageView.image = selectedImage;
}
Confirm button:
- (IBAction) confirmPhoto:(id)sender
{
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];
}
I used these codes to try out on ONE image, so it will be working perfectly fine.
But after some time, i found out that i have to allow the user to store more than one photos. My codes are unable to do that because i somehow ‘hardcode’ the file name which is SavedImage.png and the new image will simply replace the old image.
I have thought of a method to solve this, which is by using a counter to name the images when i store them into my application.
Something like that:
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png", counter]];
But this will not be a good naming convention for my images. I want to save them with proper names. What i have thought of, is that when the user tap on the confirm button, the application will display a message box that prompts and allows user to key in the name of the image that’s being selected. The image will then be saved as the name that the user have entered.
Create a little ViewController with an UITextField and 2 buttons for OK and ABORT and show it with a UIPopOverController. You should be aware, that you must check for legal filenames, check for files already existing (and allow overwriting).