Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

How to pass picture/movie to other viewcontroller?

Hi guys, I want to share the picture/movie in the Ribbit app with other view controllers. I want to pass the picture taken with pickercontroller in cameravc.m to aanvraagvc.m;

For the cameravc.m i have:

//  CameraViewController.m
//

#import "CameraViewController.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import "AanvraagViewController.h"
#import <Parse/Parse.h>

@interface CameraViewController ()

@end

@implementation CameraViewController
@synthesize id;

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.friendsRelation = [[PFUser currentUser] objectForKey:@"friendsRelation"];

    PFQuery *query = [self.friendsRelation query];
    [query orderByAscending:@"username"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (error) {
            NSLog(@"Error %@ %@", error, [error userInfo]);
        }
        else {
            self.friends = objects;
            [self.tableView reloadData];
        }
    }];

    if (self.image == nil && [self.videoFilePath length] == 0) {
        self.imagePicker = [[UIImagePickerController alloc] init];
        self.imagePicker.delegate = self;
        self.imagePicker.allowsEditing = NO;
        self.imagePicker.videoMaximumDuration = 10;

        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        }
        else {
            self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }

        self.imagePicker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:self.imagePicker.sourceType];

        [self presentViewController:self.imagePicker animated:NO completion:nil];
    }
}


#pragma mark - Table view delegate



#pragma mark - Image Picker Controller delegate

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];

    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        // A photo was taken/selected!
        self.image = [info objectForKey:UIImagePickerControllerOriginalImage];
        if (self.imagePicker.sourceType == UIImagePickerControllerSourceTypeCamera) {
            // Save the image!
            UIImageWriteToSavedPhotosAlbum(self.image, nil, nil, nil);
        }
    }
    else {
        // A video was taken/selected!
        self.videoFilePath = (__bridge NSString *)([[info objectForKey:UIImagePickerControllerMediaURL] path]);
        if (self.imagePicker.sourceType == UIImagePickerControllerSourceTypeCamera) {
            // Save the video!
            if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(self.videoFilePath)) {
                UISaveVideoAtPathToSavedPhotosAlbum(self.videoFilePath, nil, nil, nil);
            }
        }
    }

    [self uploadMessage];
    CameraViewController *cameraViewController = [[CameraViewController alloc] initWithNib:@"CameraViewController" bundle:nil];
    cameraViewController.delegate = self
    [[self navigationController] pushViewController:cameraViewController animated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)uploadMessage {

    NSData *fileData;
    NSString *fileName;
    NSString *fileType;

    if (self.image != nil) {
        UIImage *newImage = [self resizeImage:self.image toWidth:320.0f andHeight:480.0f];
        fileData = UIImagePNGRepresentation(newImage);
        fileName = @"image.png";
        fileType = @"image";
    }
    else {
        fileData = [NSData dataWithContentsOfFile:self.videoFilePath];
        fileName = @"video.mov";
        fileType = @"video";
    }

    PFFile *file = [PFFile fileWithName:fileName data:fileData];
    [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (error) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"An error occurred!"
                                                                message:@"Please try sending your message again."
                                                               delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alertView show];
        }
        else {



//            onderdeelAanvraag[@"file"] = file;
//            onderdeelAanvraag[@"fileType"] = fileType;
//            onderdeelAanvraag[@"recipientIDs"] = self.recipients;
//            

                if (error) {
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"An error occurred!"
                                                                        message:@"Please try sending your message again."
                                                                       delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
                    [alertView show];
                }
                else {
                    // Everything was successful!
                    [self.delegate addItemViewController:self didFinishEnteringItem:fileName];
                    [self reset];
                }
//            }];
        }
    }];
}

- (void)reset {
    self.image = nil;
    self.videoFilePath = nil;
    [self.recipients removeAllObjects];
}

- (UIImage *)resizeImage:(UIImage *)image toWidth:(float)width andHeight:(float)height {
    CGSize newSize = CGSizeMake(width, height);
    CGRect newRectangle = CGRectMake(0, 0, width, height);
    UIGraphicsBeginImageContext(newSize);
    [self.image drawInRect:newRectangle];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return resizedImage;
}

@end ``` 

For the aanvraagvc.m I have;

```//
//  AanvraagViewController.m
//  Auto-onderdelen Garage
//
//  Created by BLANCO on 01-05-14.
//  Copyright (c) 2014 Sinan Karakurt. All rights reserved.
//

#import "AanvraagViewController.h"
#import <Parse/Parse.h>




@interface AanvraagViewController ()

@end

@implementation AanvraagViewController



- (void)viewDidLoad
{
    [super viewDidLoad];




    _onderdeelOmschrijvingField.delegate= self;
    _autoOmschrijvingField.delegate = self;



}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_onderdeelOmschrijvingField resignFirstResponder];
    [_autoOmschrijvingField resignFirstResponder];



}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    if (textField)
    {
        [textField resignFirstResponder];
    }
    return NO;
}



- (IBAction)maakFoto:(id)sender {

    [self performSegueWithIdentifier:@"showCamera" sender:self];

}

- (IBAction)verstuurAanvraag:(id)sender {



    NSString *onderdeelOmschrijving  = self.onderdeelOmschrijvingField.text ;
    NSString *autoOmschrijving = self.autoOmschrijvingField.text ;


    if  ([onderdeelOmschrijving length] == 0 ||
         [autoOmschrijving length] == 0)
    {

        UIAlertView *alertView = [[ UIAlertView alloc] initWithTitle:@"Leeg veld" message:@"Vul de lege velden in" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];

        [alertView show];
    }

    else {

        PFObject *onderdeelAanvraag = [PFObject objectWithClassName:@"Aanvragen"];
        [onderdeelAanvraag setObject:[PFUser currentUser] forKey:@"Aanvrager"];
        onderdeelAanvraag[@"OnderdeelOmschrijving"] = onderdeelOmschrijving;
        onderdeelAanvraag[@"AutoOmschrijving"] = autoOmschrijving;
        NSDate *date = [NSDate date];
        onderdeelAanvraag[@"Datum"] =date;



                    onderdeelAanvraag[@"file"] = file;
                    onderdeelAanvraag[@"fileType"] = fileType;
                    onderdeelAanvraag[@"recipientIDs"] = self.recipients;


        // Get random number between 0 and 999999
        int nummer =  arc4random() % 100000;
        NSLog(@"nieuw nummer %d", nummer);
        [onderdeelAanvraag setObject:[NSNumber numberWithInt:nummer] forKey:@"AanvraagNummer"];


        [onderdeelAanvraag saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (error) {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Sorry!" message:[error.userInfo objectForKey:@"error"] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alertView show];
            }
            else {
                [self performSegueWithIdentifier:@"showRecipients" sender:self];
            }
            }];

        }
}

- (void)addItemViewController:(CameraViewController *)controller didFinishEnteringItem:(NSString *)item
{
    NSLog(@"This was returned from ViewControllerB %@",item);
}
@end```

1 Answer

Sinan,

There are a couple of ways to pass data between view controllers, the more prevelant one is by using prepareForSegue method

  • (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

This requires that you have a property in the header file of the desination view controller to accomodate the data being passed. In your example it would the movie file (or path to the movie). In the prepareForSegue method you can get a reference to the destination view controller via the segue parameter. Then you can access the destination property using the reference and assign the value from the source view controller.

UIViewController* viewController= segue.destinationViewController //replace UIViewController with your custom view controller class viewController.movie = self.movie; //assumes movie is a property in both view controllers