2

I have looked everywhere on the internet and I havent found a single solution for me. In my app, I have a tableview and users add there own cells. In the detail view, there is a UIImageView and a place where the can take a picture. I need t o be able to save that image in the app somewhere and then after they save it, they can click the cell later on and it will show that image they took a while back.

Here is the code for the table view cell and tableview:

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath      {   
if (indexPath.row == 0) // Don't move the first row
    return NO;

return YES;
}



-(void)tableView:(UITableView *)tableView setEditing:(BOOL)editing animated:(BOOL) animated {
[super setEditing:editing animated:animated];
[tableView setEditing:editing animated:animated];
NSLog(@"EDIT BUTTON WILL BEGIN EDITING");

if (editing) {

    [self.tableView setEditing:YES animated:YES];

} else {

    [self.tableView setEditing:NO animated:YES];

}

[tableView reloadData];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSManagedObjectContext *context = [self managedObjectContext];

if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete object from database
    [context deleteObject:[self.devices objectAtIndex:indexPath.row]];

    NSError *error = nil;
    if (![context save:&error]) {
        NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]);
        return;
    }


    // Remove device from table view

    [WTStatusBar setStatusText:@"Removed" timeout:0.7 animated:YES];
    [self.devices removeObjectAtIndex:indexPath.row];
    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _devices.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    [cell.textLabel setTextColor:[UIColor grayColor]];
    [cell.textLabel setHighlightedTextColor:[UIColor whiteColor]];
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
NSManagedObject *device = [self.devices objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:@"%@", [device valueForKey:@"name"]]];
[cell.detailTextLabel setText:[device valueForKey:@"company"]];
[cell.textLabel setBackgroundColor:[UIColor clearColor]];
[cell.detailTextLabel setBackgroundColor:[UIColor clearColor]];
[cell setSelectionStyle:UITableViewCellSelectionStyleGray];

cell.backgroundView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"TableViewCell.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0]];

return cell;
}

- (NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:@selector(managedObjectContext)]) {
    context = [delegate managedObjectContext];
}
    return context;
}


- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
id ob = [_devices objectAtIndex:destinationIndexPath.row];

[_devices replaceObjectAtIndex:destinationIndexPath.row withObject:[_devices objectAtIndex:sourceIndexPath.row]];
[_devices replaceObjectAtIndex:sourceIndexPath.row withObject:ob];
}

Here is the code for saving it to the tableview:

- (IBAction)save:(id)sender {
    NSManagedObjectContext *context = [self managedObjectContext];

    UIImage *image = resultImage.image;
    NSData *imageData = UIImagePNGRepresentation(image); //convert image into .png format.
    NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
    NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@KYRO Receipts Images/Barcode.png", resultImage]]; //add our image to the path
    [fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)
    NSLog(@"image saved");

    if (self.device) {
        // Update existing device
        [self.device setValue:self.nameOfItem.text forKey:@"name"];
        [self.device setValue:self.dateOfPurchase.text forKey:@"date"];
        [self.device setValue:self.companyOfItem.text forKey:@"company"];


    } else {
       // 
        NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Receipt" inManagedObjectContext:context];
        [newDevice setValue:self.nameOfItem.text forKey:@"name"];
        [newDevice setValue:self.dateOfPurchase.text forKey:@"date"];
        [newDevice setValue:self.companyOfItem.text forKey:@"company"];

    }

    NSError *error = nil;
    // Save the object to persistent store
    if (![context save:&error]) {
        NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }
    [WTStatusBar setStatusText:@"Saving data..." animated:YES];
    [self performSelector:@selector(setTextStatusProgress3) withObject:nil afterDelay:0.1];

        [self.navigationController popViewControllerAnimated:YES];
    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];


}
Kyle Greenlaw
  • 737
  • 1
  • 8
  • 20

2 Answers2

4

Just save it in the document's directory of the app. And store the path inside of NSUserDefaults. Then you can access it whenever/whereever you'd like:

NSData *imageData = UIImagePNGRepresentation(newImage);//Where newImage is a UIImage 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",@"cached"]];

if (![imageData writeToFile:imagePath atomically:NO]) 
{
    //failed to save
}
else
{
    //success
}

Then retrieve it from wherever you stored it, and init the image with the path:

 UIImage *customImage = [UIImage imageWithContentsOfFile:theImagePath];

//Possible duplicate here:

Storing images locally on an iOS device

Community
  • 1
  • 1
Tommy Devoy
  • 13,441
  • 3
  • 48
  • 75
0

Since you are using core data, you can also save the data into the database. Here's how you do it.

1) Alter your data model to add a image field and mark choose its type as 'Transformable'

2) Tell CoreData how to transform a database blob (NSData) into a UIImage

IDZUIImageToNSDataTransformer.h

#import <Foundation/Foundation.h>

@interface IDZUIImageToNSDataTransformer : NSValueTransformer

@end

IDZUIImageToNSDataTransformer.m

#import "IDZUIImageToNSDataTransformer.h"

@implementation IDZUIImageToNSDataTransformer


+ (BOOL)allowsReverseTransformation {
    return YES;
}

+ (Class)transformedValueClass {
    return [NSData class];
}


- (id)transformedValue:(id)value {
        // You could use UIImagePNGRepresentation here!
    NSData *data = UIImageJPEGRepresentation(value, 1.0);    
    return data;
}


- (id)reverseTransformedValue:(id)value {
    UIImage *uiImage = [[UIImage alloc] initWithData:value];
    return [uiImage autorelease];
}

@end

3) Update your save code

- (IBAction)save:(id)sender {
    NSManagedObjectContext *context = [self managedObjectContext];
    NSManagedObject* device;
    if(self.device)
        device = self.device;
    else 
        device = [NSEntityDescription insertNewObjectForEntityForName:@"Receipt"
                  inManagedObjectContext:context];

    [device setValue:self.nameOfItem.text forKey:@"name"];
    [device setValue:self.dateOfPurchase.text forKey:@"date"];
    [device setValue:self.companyOfItem.text forKey:@"company"];
    [device setValue:resultImage.image forKey:@"image"];

    NSError *error = nil;
    // Save the object to persistent store
    if (![context save:&error]) {
        NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }
    [WTStatusBar setStatusText:@"Saving data..." animated:YES];
    [self performSelector:@selector(setTextStatusProgress3) withObject:nil afterDelay:0.1];

        [self.navigationController popViewControllerAnimated:YES];
    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];


}
idz
  • 12,825
  • 1
  • 29
  • 40
  • I put all he code in but nothing is happening. The image does not show when the table view cell i made is clicked – Kyle Greenlaw May 02 '13 at 19:22
  • You'll need to update the code that shows the "detail" view to show the image from the database. – idz May 03 '13 at 00:46
  • Sorry but im new to this, how exactly would i do this :P Thanks! – Kyle Greenlaw May 07 '13 at 19:47
  • I can't tell you exactly, because I can't see your code ;-) But you have a master view controller and a detail view controller. At some point when the use clicks on a row in the master you push the detail view controller. Somewhere in that code you set the name, date and company. Wherever you do that you need to also set the image. – idz May 07 '13 at 21:01