Retrieve all images from NSDocumentDirectory and storing into an array - objective-c

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];

Related

How to save and load multiple photos into my local app in Objective C?

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
image=[info objectForKey:UIImagePickerControllerOriginalImage];
[self.images addObject:image];
[self.maintable reloadData];
[self dismissViewControllerAnimated:YES completion:NULL];
}
-(IBAction)savebutton:(id)sender{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,
NSUserDomainMask , YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"MyImages"]];
for (int i=0; i<_images.count; i++) {
image=[_images objectAtIndex:i];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
NSLog(#"saved");
}
}
- (UIImage*)loadImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);`
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"MyImage.png"] ];
image = [UIImage imageWithContentsOfFile:path];
if(image != nil){
[self.images addObject:image];
}
return image;
}
You are on correct track,
On save button action, save images document directory's particular path and save image name in one array which you need to save in core data or preference whatever you preferred in your app
like this..
NSString *strImageName = #"image.png"
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent: strImageName];
// Above you can give your custom path like #"App_Name/imageName" for unique identification
[pngData writeToFile:filePath atomically:YES];
[arrCoreData addObject: strImageName];
Once you have done(saved all your images then save image name in preference)
like this
NSData *data = [NSKeyedArchiver archivedDataWithRootObject: arrCoreData];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:#"MyImageArray"];
When you want to fetch images and display it again,
You may follow this flow:
NSData *mainCatData = [[NSUserDefaults standardUserDefaults] objectForKey:#"MyImageArray"];
arrCoreData = [NSKeyedUnarchiver unarchiveObjectWithData:mainCatData];
Then using these images name you may fetch images back and display as you want..
To load image from document directory, You may use this function
- (UIImage*)loadImage:(NSString)strImageName{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithString: #"AppName/%#", strImageName] ];
UIImage* image = [UIImage imageWithContentsOfFile:path];
return image;
}
Hope it will help you :)
I did it and worked on my app:)
- (void)loadImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *fileArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
for (int i=0; i<fileArray.count; i++) {
NSString* path = [documentsDirectory stringByAppendingPathComponent:fileArray[i]];
image = [UIImage imageWithContentsOfFile:path];
[self.images addObject:image];
}
}
-(IBAction)savebutton:(id)sender{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask , YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
for (int i=0; i<_images.count; i++) {
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"MyImages%d", i]];
image=[_images objectAtIndex:i];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
NSLog(#"saved");
}
}

Saving data from Twitter feed parsed with JSON into Plist

I have a UITableView populated by a feed from searchtwitter.com. I also have a details table with an image and UILabel. I have all this working, but I want to add a UIButton on the detail page that will save the UIImage and the label into a property list. I'm very new to this; here is what I have so far (not working).
- (IBAction)SaveFriend:(id)sender
{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [path objectAtIndex:0];
NSString *plistPath = [documentDirectory stringByAppendingPathComponent:#"TwitterFriends.plist"];
NSDictionary * tweet = [[NSDictionary alloc]init];
NSString *text = [tweet objectForKey:#"from_user"];
NSString *user = [tweet objectForKey:#"from_user_name"];
personName.text = text;
personInfo.text = user;
// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: personName, personInfo, nil] forKeys:[NSArray arrayWithObjects: #"Name", #"info", nil]];
NSString *error = nil;
// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
// check is plistData exists
if(plistData)
{
// write plistData to our Data.plist file
[tweet writeToFile:plistPath atomically:YES];
}
else
{
NSLog(#"Error in saveData: %#", error);
[error release];
}
}
Instead of using a .plist, try using an NSArray or NSMutableArray and then the writeToFile method. For example:
NSMutableArray *temp = [NSMutableArray new];
[temp addObject:image];
[temp addObject:label];
[temp writeToFile:[self saveFilePath:#"filename"] atomically:YES];
//Returns the saved information path
- (NSString*) saveFilePath: (NSString *) add
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSString *filename = [path stringByAppendingPathComponent:add];
return filename;
}

trying to save image picked to appdocs-not happening

I'm really struggling with this,Day three of the unending quest to save and load an image in my app. I'm picking an image from camera roll and trying to save it to the device via the appsdocsdirectory.
in the Appdelegate.m I have:
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
}
in the class I want to save and load the image (picked from camera roll into UI imageView)
- (IBAction)save:(id)sender {
UIImage *myImage = [imageView image];
NSData *data = UIImagePNGRepresentation(myImage);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *appDocsDirectory = [paths objectAtIndex:0];
}
- (IBAction)load:(id)sender {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *appDocsDirectory = [paths objectAtIndex:0];
UIImage* thumImage = [UIImage imageWithContentsOfFile: [NSString stringWithFormat:#"%#/%#.png", appDocsDirectory, #"myNewFile"]];
}
#end
I also imported Appdelegate.h, in this class, not sure if that was needed or correct?Now I have finally got rid of all errors and no exceptions being thrown but now my problem is nothing happens when I try to save the image and load it. I'm also getting yellow triangles telling me i have unused veriables in load UIImage* thumImage NSString *appDocsDirectory & NSData *data so I may have made a royal hash of this.
This is how I did it in one of my project.
I get the picture with the delegate method ot the imagePickerController :
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
pictureInfo = info;
}
Then I save it like this :
-(void)createPin
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pinFolderName = [NSString stringWithFormat:#"%f",[[NSDate date] timeIntervalSince1970]];
NSString *pinFolderPath = [documentsDirectory stringByAppendingPathComponent:pinFolderName];
[fileManager createDirectoryAtPath:pinFolderPath withIntermediateDirectories:YES attributes:nil error:NULL];
self.fullsizePath = [pinFolderPath stringByAppendingPathComponent:#"fullsize.png"];
NSString *mediaType = [pictureInfo objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.image"]){
UIImage *fullsizeImage = [pictureInfo objectForKey:UIImagePickerControllerEditedImage];
NSData *fullsizeData = UIImagePNGRepresentation(fullsizeImage);
[fullsizeData writeToFile:self.fullsizePath atomically:YES];
}
}
Hope you can start from there.
If you need any explanations or help, feel free to ask
I have used NSuser defaults, all sorted

Create plist file via code

I want to create a plist file like this:
in code, and then it will be in the Caches folder.
I already know how to fetch the data.
You can do it like this:
//Create a Mutant Dictionary
NSMutableDictionary *theMutantDict = [[NSMutableDictionary alloc] init];
//Fill it with data
[theMutantDict setObject:#"John" forKey:#"Name"];
[theMutantDict setObject:#"Doe" forKey:#"Lastname"];
//Then search for cache dir
NSString *libraryDir = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
NSString *cacheDir = [libraryDir stringByAppendingPathComponent:#"Caches"];
//Then write the file
NSString *filePath = [cacheDir stringByAppendingString:#"/TheFile.plist"];
[theMutantDict writeToFile:filePath atomically:YES];
Just use the writeToFile-method of NSArray to store the array in a plist and arrayWithContentsOfFile to load it.
[self.array writeToFile:path atomically:YES];
self.array = [[NSArray arrayWithContentsOfFile:path];
// or in case you need to add/remove objects (NSMutableArray):
self.array = [[[NSArray arrayWithContentsOfFile:path] mutableCopy] autorelease];
If you got your data stored in an NSArray it's as easy as this:
// filling array with data ...
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = [paths objectAtIndex:0];
NSString *plistPath = [cachePath stringByAppendingPathComponent:#"my_nsarray_data.plist"];
[klasserArray writeToFile:plistPath atomically:YES];
// other stuff ...

How to upload image, which is not saved on the device to the dropbox account?(IOS)

Dropbox restClient saves only files. So i want to save the image in local folder first and then to upload it, as a result it saves file, but it is corrupted.
NSString *localPath = [[NSBundle mainBundle] pathForResource:#"Info" ofType:#"plist"];
NSString *jpegFilePath = [NSString stringWithFormat:#"%#/test.jpeg",localPath];
NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];
[data2 writeToFile:jpegFilePath atomically:YES];
NSString *filename = #"test.jpeg";
NSString *destDir = #"/";
[[self restClient] uploadFile:filename toPath:destDir
withParentRev:nil fromPath:localPath];
I am an idiot, solved
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingString:#"test.jpg"];
NSData * data = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];
[data writeToFile:path atomically:YES];
[self.restClient uploadFile:#"test.jpg" toPath:#"/" withParentRev:nil fromPath:path];
you will have to call DBRestClient methods from the main thread or a thread that has a run loop. Otherwise the delegate methods will not be called.
what you will have to do is first alloc init yoir DBRestClient object then make it's delegate self and then you can easily upload your file.below is an example
NSString *destDir = #"/";
restClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession]];
restClient.delegate = self;
[restClient uploadFile:yourfilename toPath:destDir withParentRev:nil fromPath:sourcepath];
Happy Coding!!!!!!
You can't save into the bundle. You should use documents or cache folder:
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];