Search code examples
iosxcodeuiviewuiimageviewscreenshot

Moving an image over a segue to load into another UIImageView


I am currently building an application for iOS. I am trying to save what the user was currently looking at so that I can load that up for the next view. I know how to save images via

 CGSize size = [self.tableView bounds].size;
        UIGraphicsBeginImageContext(size);
        [[self.tableView layer] renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

However I do not know how to move them to the next view controller. For some reason, the above refuses to load it up in an image view within the next view controller.

Solved

_incommingImage is an image view.

I save it like this.

 NSData *imageData = UIImageJPEGRepresentation(newImage, 1.0);
        NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                               NSUserDomainMask,
                                                               YES);
        NSString *path = [[pathArr objectAtIndex:0]
                          stringByAppendingPathComponent:@"img.data" ];
[imageData writeToFile:path atomically:YES];

I load it up then with this.

 NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                           NSUserDomainMask,
                                                           YES);
    NSString *path = [[pathArr objectAtIndex:0]
                      stringByAppendingPathComponent:@"img.data" ];
    NSData *retrievedData = [NSData dataWithContentsOfFile:path];
    _incommingImage.image = [UIImage imageWithData:retrievedData];
       [_incommingImage release];

Solution

  • I agree with Robert.

    FirstViewController.m:

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
        if ([segue.identifier isEqualToString:@"Your_Identifier"]) {
            SecondViewController *secondVC = segue.destinationViewController;
            secondVC.incommingImage = myImage;
        }
    }
    

    SecondViewController.h:

    @property (strong, nonatomic) UIImage *incommingImage;
    

    Once your SecondViewController appears, the image will automatically be set to incommingImage. Be sure to set the identifier of your segue on the storyboard to match the identifier under prepareForSegue.