Displaying photos from NSDocumentDirectory - objective-c

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.
- (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.
- (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?

First of all, while storing the image in Documents folder, try storing them with a naming convention like keep a counter variable and give your images names according to it. Some thing like this:
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"%d.png", counter]];
Now, once you've all images stored in documents folder and wish to get all of them you can get them by writing this code:
-(NSMutableArray *)GetImage:(NSMutableArray *)arrayImgNames
{
NSMutableArray *tempArray;
for(int i=0;i<[arrayImgNames count]; i++)
{
NSArray *paths1 = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths1 objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent: [arrayImgNames objectAtIndex:i]];
[tempArray addObject:[[UIImage alloc] initWithContentsOfFile:filePath]];
return tempArray;
}
}
Once you've got all images you can display them as thumbnails and then when you wish to delete an image use this method:
-(int)removeImage:(NSString*)FileName1
{
NSFileManager *filemanager=[NSFileManager defaultManager];
NSArray *path1=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentdirectory = [path1 objectAtIndex:0];
NSString *filepath=[documentdirectory stringByAppendingPathComponent:FileName1];
if([filemanager fileExistsAtPath:filepath]==TRUE)
{
[filemanager removeItemAtPath:filepath error:nil];
}
return 0;
}
I hope this helps you.
To Populate the table with image you'll need a custom cell. You can refer a tutorial by Apple called AdvancedTableViewCells. It will show you how can you populate your table with images. They have a main thumbnail in every row. You have to customize it and make it 3 or 4 thumbnails as per your requirement. Other than that remove everything from that custom cell.

Related

How can I share a gif image using UIActivityViewController with Objective-C?

I have an app that lets the user record a short video and generate a gif image. Now I want to give the user the possibility to share that gif image using UIActivityViewController, I've done this:
UIImage *img = ...
NSArray *objectsToShare = #[img];
UIActivityViewController *avc = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
NSArray *excludeActivities = #[UIActivityTypePrint];
avc.excludedActivityTypes = excludeActivities;
[self presentViewController:avc animated:YES completion:nil];
The problem is that this only shares an static .jpg image (like the first frame of the original .gif image).
On the other hand, the user can save the gif image to the camera roll, and from there it is possible to share it as a .gif. So how can I do the same thing but from my own app?
Thanks in advance.
Ok, I managed to do this, and now I can share gif images by email, but I thing there is something left to do with Twitter.
UIImage *img = ...;
NSError *err;
NSData *imgData = [imageSerialization animatedGIFDataWithImage:img error:&err];
NSLog(#"%#", err);
NSArray *objectsToShare = #[imgData];
UIActivityViewController *avc = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
NSArray *excludeActivities = #[UIActivityTypePrint, UIActivityTypeAssignToContact];
avc.excludedActivityTypes = excludeActivities;
[self presentViewController:avc animated:YES completion:nil];
Share GIF File For WhatsApp:
NSURL *imageUrl =[self.ImageArray objectAtIndex:currentPhotoIndex];
NSString *path=imageUrl.absoluteString;
NSArray *strings = [path componentsSeparatedByString:#"/"];
NSString *mygif=[strings objectAtIndex:strings.count-1];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *dataPath = [documentsPath stringByAppendingPathComponent:#"/MrHRamani"];
NSString *filePath = [dataPath stringByAppendingPathComponent:mygif];
NSURL *urll=[NSURL fileURLWithPath:filePath];
NSLog(#"imag %#",imageUrl);
self.documentationInteractionController.delegate = self;
self.documentationInteractionController.UTI = #"net.whatsapp.image";
self.documentationInteractionController = [self setupControllerWithURL:urll usingDelegate:self];
[self.documentationInteractionController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];

How to save an image dynamically

I am using photo library in my app. And after selecting image from photo library or camera i want to save that image into my Documents folder. So here i want to give name to that image while saving is it possible to set name to the selected image? If means please let me know. I am trying that only if possible i will post that.Thank you.
This is how I do it.. I'm copying and pasting my code so there's some additional functionality.
// image is a UIImage
// inputText is the user selected imagename
// date is a string I inserting to make pictures a unique identifier (i.e. no duplicate names)
NSData *imageData1 = UIImageJPEGRepresentation(image, 1.0);
NSString *imageFilename = [NSString stringWithFormat:#"%#-%#.jpg", inputText,date];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [NSString stringWithFormat:#"%#/%#", [paths objectAtIndex:0], imageFilename];
if([imageData1 writeToFile:path atomically:YES]){
NSLog(#"Write to Document folder success filename = %#",path);
}
Use following :
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *photoImage = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
NSString *savedDoc = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/myImageName.png"];
BOOL status = [[NSFileManager defaultManager] fileExistsAtPath:savedDoc];
if(status){
[[NSFileManager defaultManager] removeItemAtPath:savedDoc error:nil];
}
[UIImagePNGRepresentation(photoImage) writeToFile:savedDoc atomically:YES];
[picker dismissModalViewControllerAnimated:YES];
}
You can set any desired name when saving to document directory.
Declare an integer counterNo and initialize it to 0. And increase its value to change name dynamically.
UIImage *photoImage = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
counterNo++;
NSString *aaa = [NSString stringWithFormat:#"Documents/myImage-%d.png" , counterNo];
NSString *savedDoc = [NSHomeDirectory() stringByAppendingPathComponent:aaa];
BOOL status = [[NSFileManager defaultManager] fileExistsAtPath:savedDoc];
if(status){
[[NSFileManager defaultManager] removeItemAtPath:savedDoc error:nil];
}
[UIImagePNGRepresentation(photoImage) writeToFile:savedDoc atomically:YES];
[picker dismissModalViewControllerAnimated:YES];

iOS: Saving A Picture In UIImageView

I have an app that allows the user to choose a picture from their camera roll, and display it in a UIImageView. I usually use this method to save text in text fields, and I assumed that it would work for an image as well, but I'm having some issues with it. There are no errors, but it simply does not save the image.
This is the relevant code I'm using:
.h:
#define kFilename9 #"PGdata.plist"
...
- (NSString *)dataFilePath;
.m:
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kFilename9];
}
- (void)applicationDidEnterBackground:(NSNotification *)notification {
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:image.image];
[array writeToFile:[self dataFilePath] atomically:YES];
}
- (void)viewDidLoad
{
...
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
image.image = [array objectAtIndex:0];
}
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:app];
[super viewDidLoad];
}
You have to convert the UIImage to a PNG or JPG first, using UImagePNGRepresentation or UIImageJPEGRepresentation. Those function return NSData which you can then write to a file.
You can save by following this way。
UIImage * image;//the image you want to save
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir=[paths objectAtIndex:0];
NSFileManager *filemanager=[NSFileManager defaultManager];
NSData * imagedata=UIImageJPEGRepresentation(image,1);
NSString *savePath= [docDir stringByAppendingPathComponent:#"imageName.jpg"];
BOOL isdic=NO;
BOOL isHave=[filemanager fileExistsAtPath:savePath isDirectory:&isdic];
if (isHave==YES&&isdic==NO) {
[filemanager removeItemAtPath:savePath error:nil];
}
BOOL result= [imagedata writeToFile:savePath atomically:YES];

Retrieve all images from NSDocumentDirectory and storing into an array

Currently i'm using these codes to save my images into NSDocumentDirectory. I use this counter as the naming convention for them.
- (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:[NSString stringWithFormat:#"%d.png", counter]];
UIImage *image = imageView.image;
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
}
I use this method because it's easier for me to retrieve all of them by using a loop. I want to retrieve all the images from the NSDocumentDirectory so that i can display them in another view. The following codes show how i retrieve them.
-(NSMutableArray *)GetImage:(NSMutableArray *)arrayImgNames
{
NSMutableArray *tempArray;
for(int i=0;i<[arrayImgNames count]; i++)
{
NSArray *paths1 = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths1 objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent: [arrayImgNames objectAtIndex:i]];
[tempArray addObject:[[UIImage alloc] initWithContentsOfFile:filePath]];
return tempArray;
}
}
However, i do not wish to use the counter as a naming convention for my images. I want to use proper names for them but if i do so, i will have to change my method of retrieving all the images.
Is there any other way that i can retrieve all images other than this method i mentioned?
You can retrieve files using next approach:
NSURL *url = [[AppDelegate sharedAppDelegate] applicationDocumentsDirectory];
NSError *error = nil;
NSArray *properties = [NSArray arrayWithObjects: NSURLLocalizedNameKey, NSURLLocalizedTypeDescriptionKey, nil];
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:url
includingPropertiesForKeys:properties options:(NSDirectoryEnumerationSkipsPackageDescendants)
error:&error];
In files paths to all files of documents directory will be stored. Next code will help you to get there names:
NSURL *url = [files objectAtIndex:index];
NSString *localizedName = [url lastPathComponent];

Xcode Saving NSMutableArray of String & BOOL values

I've got a little problem with an Application i am designing at the min but i'm a complete beginner, first of all a little information on what i am trying to accomplish.
I have a plist which populates an NSMutableArray which contains many values each one has a string and a BOOL inside, i can make the program save a copy of the file upon opening the app and load the data into the tableview along with an accessoryview of a checkmark.
now the checkmark works ok and you can select different items and the checkmark only appears on those items none of the others and if you inspect the log the details for each of the items check BOOL is changed but when i come to save a second time the checkmark state is not persisted for when i open the application a second time it just saves it as a 0 everytime.
here is some of my code, any help would be appreciated.
Thanks
Brad
- (void)viewDidLoad {
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"CustomChecklist.plist"];
success = [fileManager fileExistsAtPath:filePath];
NSLog(#"STATUS OF SUCCESS %d",success);
if (!success) {
NSString *path = [[NSBundle mainBundle] pathForResource:#"OriginalChecklist" ofType:#"plist"];
success = [fileManager copyItemAtPath:path toPath:filePath error:NULL];
self.dataArray = [NSMutableArray arrayWithContentsOfFile:filePath];
NSLog(#"IF STATEMENT CREATING THE FILE");
}else {
self.dataArray = [NSMutableArray arrayWithContentsOfFile:filePath];
NSLog(#"IF STATEMENT READING THE FILE");
}
NSLog(#"location information %#", filePath);
[super viewDidLoad];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *kCustomCellID = #"MyCellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCustomCellID];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCustomCellID] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
}
NSMutableDictionary *item = [dataArray objectAtIndex:indexPath.row];
cell.textLabel.text = [item objectForKey:#"text"];
[item setObject:cell forKey:#"cell"];
BOOL checked = [[item objectForKey:#"checked"] boolValue];
UIImage *image = (checked) ? [UIImage imageNamed:#"checked.png"] : [UIImage imageNamed:#"unchecked.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
button.frame = frame; // match the button's size with the image size
[button setBackgroundImage:image forState:UIControlStateNormal];
// set the button's target to this table view controller so we can interpret touch events and map that to a NSIndexSet
[button addTarget:self action:#selector(checkButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor = [UIColor clearColor];
cell.accessoryView = button;
return cell;
}
- (void)viewWillDisappear:(BOOL)animated
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savePath = [documentsDirectory stringByAppendingPathComponent:#"CustomChecklist.plist"];
NSLog(#"View Will Disappear SAVE location information %#", savePath);
[dataArray writeToFile:savePath atomically:YES];
}
BOOL is not an object, it is a primitive type. Therefore, it cannot be saved (properly) in an array or dictionary. You need to use the NSNumber class to wrap it:
[NSNumber numberWithBool:checked] //this should be added to the dictionary
I am writing this from my phone, so I can't really see all of your code. But I just wanted to say that what you are trying to achieve can probably be solved by using NSUserdefaults instead of saving a file. Have you looked into that?
Oh, and just like Evan said, bool isn't an object. Only objects can be stored in an array.
Is there a reason you are adding the cell to your dictionary? A UITableViewCell is not a property list compatible object, so it could keep your array from saving properly.