Search code examples
iosxcodeuiimagepickercontrollernsdata

Saving Image to file from imagePickerController - unable to load image


I'm not quite sure whats going wrong here, I'd really appreciate some help as I'm very stuck. This is my imagePickerController

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
        [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithLong:customphoto1] forKey:@"customphoto1count"];
        UIImage *button1Image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];


    pngData = UIImagePNGRepresentation(button1Image);
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"Button1image.png"]; //Add the file name
    [pngData writeToFile:filePath atomically:YES]; //Write the file
    [self dismissViewControllerAnimated:YES completion:NULL];
    pngData = [NSData dataWithContentsOfFile:filePath];
    UIImage *imageLoaded = [UIImage imageWithData:pngData];
    [_button1 setImage:imageLoaded forState:UIControlStateNormal];
    self.button1.clipsToBounds = YES;
    self.button1.layer.cornerRadius = (self.button1.frame.size.width / 16);//half of the width
    self.button1.layer.borderColor=[UIColor blackColor].CGColor;
    self.button1.layer.borderWidth=1.0f;
    [self dismissViewControllerAnimated:YES completion:NULL];
}

The above saves the image (as far as I believe) since _button1 is reading from imageLoaded

When the app closes and is reopened, this is the what calls the button to be displayed, and should load the picture from my NSData:

-(void)customButton1{
    if (customphoto1 == 1) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
        NSString *filePath = [documentsPath stringByAppendingPathComponent:@"Button1image.png"]; //Add the file name
        [pngData writeToFile:filePath atomically:YES];
        pngData = [NSData dataWithContentsOfFile:filePath];
        UIImage *imageLoaded1 = [UIImage imageWithData:pngData];
        NSLog(@"%@", filePath);
//        UIImage *imageload1 = [UIImage imageWithData:[newManagedObject valueForKey:@"imagesone"]];
        [_button1 setImage:imageLoaded1 forState:UIControlStateNormal];

    }
    else {
        button1ImageName = @"addnew";
    }
}

Why is my image not loading? Many thanks


Solution

  • Image was saving and loading alright all along - issue turned out to be with the buttons setImage function