Henry F
Henry F

Reputation: 4980

iOS: Saving A Picture In UIImageView

I have an app that allows the user to choose a picture from their camera roll, and display it in a UIImageView. I usually use this method to save text in text fields, and I assumed that it would work for an image as well, but I'm having some issues with it. There are no errors, but it simply does not save the image.

This is the relevant code I'm using:

.h:

#define kFilename9        @"PGdata.plist"
...
- (NSString *)dataFilePath;

.m:

- (NSString *)dataFilePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(
                                                         NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:kFilename9];
}

- (void)applicationDidEnterBackground:(NSNotification *)notification {
    NSMutableArray *array = [[NSMutableArray alloc] init];
    [array addObject:image.image];

    [array writeToFile:[self dataFilePath] atomically:YES];
}
- (void)viewDidLoad
{
    ...  

    NSString *filePath = [self dataFilePath];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
        image.image = [array objectAtIndex:0];
    }

    UIApplication *app = [UIApplication sharedApplication];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationDidEnterBackground:)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:app];

    [super viewDidLoad];

}

Upvotes: 0

Views: 281

Answers (2)

afterglow
afterglow

Reputation: 11

You can save by following this way。

UIImage * image;//the image you want to save


 NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *docDir=[paths objectAtIndex:0];

    NSFileManager *filemanager=[NSFileManager defaultManager];

    NSData   *  imagedata=UIImageJPEGRepresentation(image,1);
    NSString *savePath= [docDir stringByAppendingPathComponent:@"imageName.jpg"];

    BOOL isdic=NO;
    BOOL isHave=[filemanager fileExistsAtPath:savePath isDirectory:&isdic];
    if (isHave==YES&&isdic==NO) {
        [filemanager removeItemAtPath:savePath error:nil];
    }

   BOOL result= [imagedata writeToFile:savePath atomically:YES];

Upvotes: 1

jsd
jsd

Reputation: 7693

You have to convert the UIImage to a PNG or JPG first, using UImagePNGRepresentation or UIImageJPEGRepresentation. Those function return NSData which you can then write to a file.

Upvotes: 3

Related Questions