Encode array of images exception - objective-c

i try to encode an array with UIImages.
Then i call "save" function
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:#"SavedUserData"];
[NSKeyedArchiver archiveRootObject: self toFile:filePath];
i get exception for line
[encoder encodeObject:recipePhotoList forKey:#"recipePhotoList"]; //array with images
-[UIImage encodeWithCoder:]: unrecognized selector sent to instance 0x1b1380
2012-03-23 11:59:43.694 fishmarket[261:1a0f] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImage encodeWithCoder:]: unrecognized selector sent to instance 0x1b1380'
On 5+ iOS its working perfectly, on 4.3 i have this problem.

That's because UIImage didn't support NSCoding until iOS 5. Check the iOS 5.0 API diff.

some alternative to encode/decode UIIMage for iOS < 5.0
+ (void)saveImage:(UIImage*)image withName:(NSString*)imageName
{
if (image != nil)
{
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithString:imageName]];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
}
}
+ (UIImage*)loadImageNamed:(NSString*)imageName
{
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithString:imageName]];
UIImage* image = [UIImage imageWithContentsOfFile:path];
return image;
}
hope its help somebody.

Related

Objective-C: Saving Archived Data to File Crashes

my inquiry is this: I am saving and loading custom objects to file. Loading and creating files with the data works correctly, however, after a file has loaded, saving again crashes. Long story short, saving a file that has been loaded causes a crash upon saving.
The crash sends me to my custom objects m file:
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeInteger:*(time) forKey:#"time"];
[encoder encodeInteger:*(location) forKey:#"location"];
}
//====
Loading the data from file:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
initWithContentsOfFile:filePath];
globals.mainData = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
//====
Saving to current file
My breakpoint stop me at: NSData *data = ... //and then crashes
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:currentFileName];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:globals.mainData]; //crashes here
BOOL saved = [data writeToFile:filePath options:NSDataWritingAtomic error:nil];
if (saved) {
NSLog(#"Saved %#", currentFileName);
}else{
NSLog(#"Error - code 2 - Failure to save data");
}
Any advice would be awesome and much appreciated!

UIImage set image withfile in caches directory

I am getting nil image when i try to set image from local file path (Caches directory)
file:///......
NSString* localImagePath=#"file:///Users/mac/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/BD2135B6-5E03-4797-960E-B6C2BF2D6958/Library/Caches/myImage.jpeg"
[[UIImage alloc]initWithContentsOfFile:localImagePath];
I searched through many questions but not able to find the right way to do it.
- (IBAction)saveImage {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"savedImage.png"];
UIImage *image = imageView.image; // imageView is my image from camera
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
}
May be the issue was of url encoding so I solved this by getting the caches directory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDirectory = [paths objectAtIndex:0];
NSString *localImagePath = [cacheDirectory stringByAppendingPathComponent:#"myImage.jpeg"];
[[UIImage alloc]initWithContentsOfFile:localImagePath];

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

Reading values from a plist file

I have a UITextField and when the user hits a save button, the text should be saved into a plist file with the following code:
-(IBAction)saveButtonPressed
{
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Data.plist"]; //3
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) //4
{
//5
NSString *bundle=[[NSBundle mainBundle] pathForResource:#"Data" ofType:#"plist"];
[fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
}
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
//here add elements to data file and write data to file
[data setObject:[inkTextField text] forKey:#"inkText"];
BOOL didWrite=[data writeToFile: path atomically:YES];
if(didWrite==YES)
NSLog(#"didWrite");
else NSLog(#"nope");
[data release];
}
Then I have a UITableView and I want to load the string value of plist into the cell text field with the following code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"CellViewController"];
if (cell == nil) {
// Load the top-level objects from the custom cell XIB.
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"CellViewController" owner:self options:nil];
// Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain).
cell = [topLevelObjects objectAtIndex:0];
}
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Data.plist"]; //3
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) //4
{
//5
NSString *bundle=[[NSBundle mainBundle] pathForResource:#"Data" ofType:#"plist"];
[fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
}
NSMutableDictionary *savedInks = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
//load from savedStock example int value
NSString *value;
value = [[savedInks objectForKey:#"inkText"]stringValue];
[savedInks release];
inkTitle.text=value;
return cell;
}
When I save, I get a the log outputs didWrite, so I know it saved properly. However when I visit the tableView, I get a crash with the following error:
2011-08-19 13:56:45.717 MyApp[36067:b303] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString stringValue]: unrecognized selector sent to instance 0x4bb5fa0'
So I thought it was something to do with this line:
value = [[savedInks objectForKey:#"inkText"]stringValue];
so I tried
value = [savedInks objectForKey:#"inkText"];
but that also causes a crash but with no message. What am I doing wrong?
You should remove the 'stringValue', as you're already returning a NSString value.
In the next line, you're releasing 'savedInks', before retaining 'value'. Swap the release with the line below it and see if that works.:
NSString *value;
value = [savedInks objectForKey:#"inkText"];
inkTitle.text=value;
[savedInks release];
When savedInks is released, all of the objects within the dictionary are released as well. Setting inkTtile.text should perform a retain on value automatically.

copy all files with extension to documents directory

I am having a little bit trouble with copying files from an online place to the Documents Directory of the iPad in xcode.
The files that i want to download had to be the files with the extension 'xml'.
now i am doing this:
NSData *onlineLink = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://localhost:8888/"]];
NSString *extension = #"xml";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *contents = [fileManager contentsOfDirectoryAtPath:onlineLink error:NULL];
NSEnumerator *e = [contents objectEnumerator];
NSString *filename;
while ((filename = [e nextObject])) {
if ([[filename pathExtension] isEqualToString:extension]) {
[fileManager copyItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename toPath:documentsDirectory error:NULL]];
}
}
However this does not work, i get this error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSConcreteData fileSystemRepresentation]: unrecognized selector sent to instance 0xb000800'
Can anybody give me a hint why i am getting the error?
in the line:
NSArray *contents = [fileManager contentsOfDirectoryAtPath:onlineLink error:NULL];
contentsOfDirectoryAtPath should be an NSString, you are passing an NSData object