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 Build a Self-Destructing Message iPhone App Capturing Photo and Video Using UIImagePickerController Uploading the File and Message

The Starlord
The Starlord
886 Points

unable to upload file to parse.com

i'm unable to upload the file to parse.com, looks like for some reason source type is selected as video by default and it sets to nil, although i'm selecting the image, i tried running the project files with the tutorial it works fine but for the life of me i cant figure our whats wrong with my code...

complier jumps to error block while trying to save the file to parse.com

//
//  CameraTableViewController.m
//  Ribbit
//
//  Created by Syed Ehteshamuddin on 2015-04-16.
//  Copyright (c) 2015 techbate.com. All rights reserved.
//

#import "CameraTableViewController.h"
#import <MobileCoreServices/UTCoreTypes.h>

@interface CameraTableViewController ()

@end

@implementation CameraTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.friendsRelation = [[PFUser currentUser] objectForKey:@"friendsRelation"];
    self.recipients = [[NSMutableArray alloc]init];



//    self.imagePicker = [[UIImagePickerController alloc]init];
//    self.imagePicker.delegate = self;
//    self.imagePicker.allowsEditing = NO;
//    self.imagePicker.videoMaximumDuration = 10;
//    
//    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
//    self.imagePicker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:self.imagePicker.sourceType ];
//    [self presentViewController:self.imagePicker animated:nil completion:nil];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];


        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:nil completion:nil];

    }
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    // Return the number of rows in the section.

    return self.friends.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    PFUser * user = [self.friends objectAtIndex:indexPath.row];
    cell.textLabel.text = user.username;

    if([self.recipients containsObject:user.objectId]){
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }else{
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    // Configure the cell...

    return cell;
}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{

    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
    PFUser * user = [self.friends objectAtIndex:indexPath.row];

    UITableViewCell * cell = [self.tableView cellForRowAtIndexPath:indexPath];
    if (cell.accessoryType==UITableViewCellAccessoryCheckmark) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        [self.recipients removeObject:user.objectId];
    }else{
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        [self.recipients addObject:user.objectId];
    }
    NSLog(@"%@", self.recipients);
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - image picker controller delegate
-(void) imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:NO completion:nil];
    [self.tabBarController setSelectedIndex:0];
}

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{

    NSString * mediaType = [info objectForKey:UIImagePickerControllerMediaType];

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

    }


}
    [self dismissViewControllerAnimated:YES completion:nil];

}

#pragma mark - IBActions


- (IBAction)cancel:(id)sender {
    [self reset];
    [self.tabBarController setSelectedIndex:0];
}

- (IBAction)send:(id)sender {
    if(self.image== nil && [self.videoFilePath length]== 0){
        UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"Try Again" message:@"Please capture video or image" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
        [alertView show];
        [self presentViewController:self.imagePicker animated:NO completion:nil];
    }else{
        [self uploadMessage];
        [self.tabBarController setSelectedIndex:0];
    }

}

#pragma mark - Helpers methods

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

-(UIImage *)resizeImage:(UIImage *)image towidth:(float)width toheight:(float)height{
    CGSize size = CGSizeMake(width, height);
    CGRect rect = CGRectMake(0, 0, width, height);
    UIGraphicsBeginImageContext(size);
    [image drawInRect:rect];
    UIImage * resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return resizedImage;

}


-(void)uploadMessage{
    [self reset];
    NSData * fileData;
    NSString * fileType;
    NSString * fileName;
    if (self.image != nil) {

        UIImage * newImage = [self resizeImage:self.image towidth:320.0f toheight:480.0f];
        fileData = UIImagePNGRepresentation(newImage);
        fileType = @"image.png";
        fileName = @"image";

    }else{

        fileData = [NSData dataWithContentsOfFile:self.videoFilePath];
        fileType = @"video.mov";
        fileName = @"video";
    }

    PFFile * file = [PFFile fileWithName:fileName data:fileData];

    NSLog(@"the contents of file %@",fileName);

    [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error){
        if(error){
            UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"Error occured saving file" message:@"Please try sending your message again" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
            [alertView show];
        }else{
            PFObject * message = [PFObject objectWithClassName:@"Messages"];
            [message setObject:file forKey:@"file"];
            [message setObject:fileType forKey:@"fileType"];
            [message setObject:self.recipients forKey:@"recipientsId"];
            [message setObject:[[PFUser currentUser]objectId] forKey:@"senderId"];
            [message setObject:[[PFUser currentUser]username] forKey:@"sendName"];
            [message saveInBackgroundWithBlock:^(BOOL succeeded, NSError * error){
                if(error){
                    UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"Error occured saving message" message:@"Please try sending your message again" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
                    [alertView show];
                }else{
                    //everything went well
                    [self reset];

                }

            }];

        }

    }];
}
@end

1 Answer

Here is a full template for the social network application: Click Here.