在详细视图中保存“用户拍摄”照片,并在表视图中单击时加载它

时间:2013-05-02 00:03:51

标签: ios objective-c core-data uitableview

我在互联网上无处不在,我没有为我找到一个解决方案。在我的应用程序中,我有一个tableview,用户添加自己的单元格。在详细视图中,有一个UIImageView和一个可以拍照的地方。我需要能够在应用程序的某个地方保存该图像,然后在保存后,他们可以稍后单击该单元格,它将显示他们花了一段时间回来的图像。

以下是表格视图单元格和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];
}

以下是将其保存到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];


}

2 个答案:

答案 0 :(得分:4)

只需将其保存在应用程序的文档目录中即可。并存储NSUserDefaults内部的路径。然后,您可以随时随地访问它:

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
}

然后从存储它的任何地方检索它,并使用路径:

初始化图像
 UIImage *customImage = [UIImage imageWithContentsOfFile:theImagePath];

//这里可能重复:

Storing images locally on an iOS device

答案 1 :(得分:0)

由于您使用的是核心数据,因此您也可以将数据保存到数据库中。这是你如何做到的。

1)更改数据模型以添加image字段并选择其类型为“可转换”

2)告诉CoreData如何将数据库blob(NSData)转换为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)更新您的保存代码

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


}