How to save and load multiple photos into my local app in Objective C? - 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");
}
}

Related

How do I download an image from a URL and save it to my computer?

How would I download an image from a URL, and have that saved to the computer using Objective-C? This is what I got so far:
NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage *imageFromURL = [self getImageFromURL:#"https://www.google.com/images/srpr/logo11w.png"];
[self saveImage:imageFromURL withFileName:#"Google Logo" ofType:#"png" inDirectory:documentsDirectoryPath];
UIImage *imageFromWeb = [self loadImage:#"Google Logo" ofType:#"png" inDirectory:documentsDirectoryPath];
Xcode complains about UIIMage, trying to replace with NSImage. It also complains about an undeclared identifier 'self'.
I need to make an HTTP call to perform this as well. Explain this to me like I'm 5.
Here is the code to Save the image into document Directory.
-(void)saveImagesInLocalDirectory
{
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imgName = #"image.png";
NSString *imgURL = #"www.example.com/image/image.png";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *writablePath = [documentsDirectoryPath stringByAppendingPathComponent:imgName];
if(![fileManager fileExistsAtPath:writablePath]){
// file doesn't exist
NSLog(#"file doesn't exist");
if (imgName) {
//save Image From URL
[self getImageFromURLAndSaveItToLocalData:imgName fileURL:imgURL inDirectory:documentsDirectoryPath];
}
}
else{
// file exist
NSLog(#"file exist");
}
}
-(void) getImageFromURLAndSaveItToLocalData:(NSString *)imageName fileURL:(NSString *)fileURL inDirectory:(NSString *)directoryPath {
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
NSError *error = nil;
[data writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#", imageName]] options:NSAtomicWrite error:&error];
if (error) {
NSLog(#"Error Writing File : %#",error);
}else{
NSLog(#"Image %# Saved SuccessFully",imageName);
}
}
And this is the one method code..
-(void)saveImagesInLocalDirectory
{
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imgName = #"image.png";
NSString *imgURL = #"www.example.com/image/image.png";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *writablePath = [documentsDirectoryPath stringByAppendingPathComponent:imgName];
if(![fileManager fileExistsAtPath:writablePath]){
// file doesn't exist
NSLog(#"file doesn't exist");
//save Image From URL
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString: imgURL]];
NSError *error = nil;
[data writeToFile:[documentsDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#", imgName]] options:NSAtomicWrite error:&error];
if (error) {
NSLog(#"Error Writing File : %#",error);
}else{
NSLog(#"Image %# Saved SuccessFully",imgName);
}
}
else{
// file exist
NSLog(#"file exist");
}
}
This is my solution!
+(BOOL)downloadMedia :(NSString*)url_ :(NSString*)name{
NSString *stringURL = url_;
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,name];
[urlData writeToFile:filePath atomically:YES];
return YES;
}
return NO;
}
+(UIImage*)loadMedia :(NSString*)name{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:name];
UIImage *img_ = [UIImage imageWithContentsOfFile:getImagePath];
return img_;
}

Saving NSString with writeToFile will only save to one location

Using the code below is the only way I can get writeToFile to actually save a file. It outputs to this directory:
/Users/Eric/Library/Containers/net.ericmann.Event-Gadget-Workshop-App/Data/Documents/gadget.ics
- (IBAction)Saved:(id)sender {
[self writeToTextFile];
//mySaved.stringValue = [NSString stringWithFormat:#"Saved!"];
}
-(void) writeToTextFile{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//NSString *pathToDesktop = [NSString stringWithFormat:#"/Users/%#/Desktop", NSUserName()];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/gadget.ics", documentsDirectory];
//create content - four lines of text
NSString *content = myOutput.stringValue;
//save content to the documents directory
[content writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
mySaved.stringValue = fileName;
myTestBox.stringValue = fileName;
}
Now, if I use the code below, nothing will write. I have the test file name output, and it's pointing here:
/Users/Eric/Desktop/gadget.ics
-(void) writeToTextFile{
//get the documents directory:
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
//NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pathToDesktop = [NSString stringWithFormat:#"/Users/%#/Desktop", NSUserName()];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/gadget.ics", pathToDesktop];
//create content - four lines of text
NSString *content = myOutput.stringValue;
//save content to the documents directory
[content writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
mySaved.stringValue = fileName;
myTestBox.stringValue = fileName;
You will likely end up figuring out a solution if you actually make use of the error parameter there in the "writeToFile" method:
e.g.:
NSError * error = NULL;
BOOL success = [content writeToFile:fileName atomically:NO encoding:NSUTF8StringEncoding error:&error];
if(success == NO)
{
NSLog( #"error saving to %# - %#", fileName, [error localizedDescription] );
}

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

UIImageJPEGRepresentation throws EXC BAD ACCESS

I have function, which received 2 arguments - image and number. Function below throws EXC BAD ACCESS on line "imgData = UIImageJPEGRepresentation(image, 1.0);". I don't know why :-( Any ideas?
- (void)saveImages:(UIImage*)image row:(int)row {
if (image != nil) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path1 = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat:#"%i.JPEG", row]];
NSString* path2 = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat:#"%is.JPEG", row]];
NSData* imgData;
imgData = UIImageJPEGRepresentation(image, 1.0);
[imgData writeToFile:path1 atomically:YES];
[self rotateIcon:image];
image = [self imageWithImage:image];
NSData* smalImgData = UIImageJPEGRepresentation(image, 1.0);
[smalImgData writeToFile:path2 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];