Tuesday, August 14, 2012

Working with Camera and Photo Library for iOS app

In this section, i will be describing you how to take a picture from camera inside your iOS app and how to store and select images from your iOS device photo library to the app of yours.
For this section we will be using UIImagePickerController class which needs UIImagePickerControllerDelegate and UINavigationControllerDelegate protocols to be defined.

1. Add MobileCoreServices framework to your project and add import
          #import <MobileCoreServices/MobileCoreServices.h>
2.Include <UIImagePickerControllerDelegate,UINavigationControllerDelegate> in .h file.
3. Lets declare some custom methods :
       - (void)takePictureFromCamera; // call it if you want to take a picture from camera
       - (void)usePictureFromCameraLibrary; // call it if you want to use picture from your device's photo library
Note : Best practice is to use UIActionSheet for displaying above two options so that user will have ease to choose pictures how they want.
  define bool variable:   BOOL newImage;  // its a flag to know which method is called
4. Now lets write custom method definition :


   - (void)takePictureFromCamera{
    /// First, lets check whether your device has a camera features or not
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType =UIImagePickerControllerSourceTypeCamera;
        imagePicker.mediaTypes = [NSArray arrayWithObjects:  (NSString *) kUTTypeImage, nil];
        imagePicker.allowsEditing = NO;
        [self presentModalViewController:imagePicker animated:YES];
           newImage = YES;  // here , bool yes means this is a camera source
    }
    else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Current running version of Device doesnot support Camera features." message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show];
    }
}
5. Before using the next method , you need to know for which device (iPad or iPhone) you are using this method? If its for iPhone then it will be straightforward like above, we simple use presentModalViewController to display camera library . But if its for iPad, then we generally present photo library in UIPopOverController so that it will be well suited .
    /------------ For iPad Only -------------------/
    - Include <UIPopoverControllerDelegate>
    - declare and synthesize @property(nonatomic,retain) UIPopoverController *imagePopController;
  /-------------------------------------------------/
- (void)usePictureFromCameraLibrary{
    /------------include for iPad Only -------------------/
    if ([self.imagePopController isPopoverVisible]) {
        [self.imagePopController dismissPopoverAnimated:YES];
      
    } else {  / -----------------------------------------/
       // if you are using this method for iPhone, start writing codes from here else proceed with top
     /// First, lets check whether your device has a photo album features or not 
        if ([UIImagePickerController isSourceTypeAvailable:  UIImagePickerControllerSourceTypeSavedPhotosAlbum])
        {
            UIImagePickerController *imagePicker =   [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            imagePicker.mediaTypes = [NSArray arrayWithObjects:(NSString *) kUTTypeImage,  nil];
            imagePicker.allowsEditing = NO;
            newImage = NO;
             /------------ For iPad Only -------------------/
            self.imagePopController = [[UIPopoverController alloc]  
                                                       initWithContentViewController:imagePicker];                   
            self.imagePopController.delegate = self;
            [self.imagePopController   presentPopoverFromBarButtonItem:methodTriggeringBtn
            permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
         *methodTriggeringBtn = your custom button from where you want to show pop up
              / -------------End of code for iPad----------------------------/
          /------------ For iPhone Only -------------------/
           [self presentModalViewController:imagePicker animated:YES];
           / -------------End of code for iPhone----------------------------/
        }
    }
}

5.Now since we have integrated our custom methods, lets handle the UIImagePickerControllerDelegate methods :
    // delegate method if picture has taken or choosen
   -(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info{

      /------------ include For iPad Only -------------------/

   if ([self.imagePopController isPopoverVisible])
    [self.imagePopController dismissPopoverAnimated:true];
    / ----------------------------------------------------------/
     NSString *mediaType = [info  objectForKey:UIImagePickerControllerMediaType];
       if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
          yourImageView.image = image; // use picture in your app
         // Now , lets check whether this picture is taken from camera or photo library? If its from Camera then save newly taken picture to device photo library
        if (newImage){
            [self dismissModalViewControllerAnimated:YES];
            UIImageWriteToSavedPhotosAlbum(image, self,@selector(image:finishedSavingWithError:contextInfo:),  nil);
        }
        }
    else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
    {
        // Code here to support video if enabled
    }
}
// Following method is called if an error occured while saving newly taken pictures
-(void)image:(UIImage *)image finishedSavingWithError:(NSError *)error
 contextInfo:(void *)contextInfo{

    if (error) {  UIAlertView *alert = [[UIAlertView alloc]  initWithTitle: @"Save failed"
                                                      message: @"Failed to save image"   delegate: nil
                                                   cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
      
    }
}

// At last include the following delegate method, which is called if the user cancels the image picker camera session without taking a picture or making an image selection.
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissModalViewControllerAnimated:YES];
}

No comments:

Post a Comment