Search code examples
iosxcodeviewdidload

How do I load a saved image using ViewDidLoad


I'm making a painting app, and I currently have the app at a point where it saves drawings, but it still can't load the drawings back into the view once the app has quit or switched views.

I'm saving the image with this:

-(IBAction)saveImage:(id)sender
{
    UIImage *saveImage = drawImage.image;

    NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(saveImage)];


    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:imageData forKey:@"image"];
    [defaults synchronize];

}

Question

How do I load imageData into the view? I'm assuming I can do it in viewDidLoad. Can I?


Solution

  • Your saving code looks fine.

    To read back the image you would do this:

    NSData* imageData = [[NSUserDefaults standardUserDefaults] objectForKey:@"image"];
    UIImage* image = [UIImage imageWithData:imageData];
    

    And yes you can do it in viewDidLoad or viewDidAppear/viewWillAppear or anywhere it is appropriate, it really depends on the use case.