How to Use the Camera in Your IOS Program

by A-Nony-Mus in Circuits > Apple

63309 Views, 15 Favorites, 0 Comments

How to Use the Camera in Your IOS Program

iPadFinal.png
Ever wondered how to use the camera in your apps you create for iOS?
Wonder no longer! The purpose of this 'ible is to educate you on one one of the ways to access and use the camera in your iOS app. This is by far the most simplistic solution and does not include all the bells and whistles other approaches offer (such as controlling the quality).

In this 'ible we will make an application that:
  • gives us access to all cameras on a device
  • allows us to save pictures and videos we take
  • allows us to see the last picture taken
*Please note, you will only be able to use this app on devices that have cameras on them (and no, the simulators do not have access to any cameras on your computer).*

Create New Project

Screen Shot 2013-01-04 at 7.52.17 PM.png
Screen Shot 2013-01-04 at 7.53.09 PM.png
I went over how to get Xcode in my previous 'ible: Creating your first iOS app, check it out if you don't have Xcode.
  • Open up Xcode. Go to File>New>Project (or press SHIFT+COMMAND+N)
  • Select "Single View Application" then Next
  • Name it what you want, I am naming it HelloCamera
  • Decide what devices you want it to run on.
  • Make sure "Use Automatic Reference Counting" and "Use Storyboards" are checked then click Next
  • Navigate to where you want to save it then click Create

Make the UI

Screen Shot 2013-01-04 at 7.57.56 PM.png
Screen Shot 2013-01-04 at 8.45.29 PM.png
Screen Shot 2013-01-04 at 8.44.41 PM.png
Screen Shot 2013-01-04 at 7.58.09 PM.png
Screen Shot 2013-01-04 at 7.59.25 PM.png
Screen Shot 2013-01-04 at 8.01.20 PM.png
Screen Shot 2013-01-04 at 8.02.13 PM.png
Screen Shot 2013-01-04 at 8.02.44 PM.png
Screen Shot 2013-01-04 at 8.03.26 PM.png
Screen Shot 2013-01-04 at 8.04.28 PM.png
Screen Shot 2013-01-04 at 8.04.41 PM.png
Screen Shot 2013-01-04 at 8.06.46 PM.png
Screen Shot 2013-01-04 at 8.06.58 PM.png
Screen Shot 2013-01-04 at 8.08.55 PM.png
Screen Shot 2013-01-04 at 8.10.03 PM.png
Screen Shot 2013-01-04 at 8.10.17 PM.png
In the HelloCamera target, scroll down untill you reach Linked Frameworks and Libraries. click the plus button, search for MobileCoreServices, then add the framework

Let's get the UI out of the way.
  • Click on your .storyboard file (if you chose universal for your devices, you'll have two, you'll be doing the same thing in each)
  • In your object library (bottom right) locate a toolbar and drag it to the bottom of the view (consult the pictures).
  • Double click on the button and rename it "Open Camera!"
  • Next locate an Image View and drag it to the view, above the toolbar
  • Now click on the Assistant Editor button
  • Make sure it is ViewController.h
  • Single click on the "Open Camera!" button
  • Right click and drag from the button to some space between @interface and @end on ViewController.h
  • You should get a little popup, set connection to Action and name it openCamera. click connect
  • Do the same with the image view, but keep it as outlet and name it imageView
That's it for the UI, now to get into the meat of the app, the code

LaunchCameraController

Screen Shot 2013-01-04 at 8.15.38 PM.png
Screen Shot 2013-01-04 at 8.17.25 PM.png
Screen Shot 2013-01-04 at 8.18.33 PM.png
Screen Shot 2013-01-04 at 8.22.02 PM.png
Screen Shot 2013-01-04 at 8.26.28 PM.png
Screen Shot 2013-01-04 at 8.32.05 PM.png
Open up ViewController.h
  • under #import <UIKit/UIKit.h> add the line #import <MobileCoreServices/MobileCoreServices.h>
  • After @interface ViewController : UIViewController add <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
This makes it a delegate of uiimagepicker and uinavigationcontroller, allowing us to handle camera events

Open ViewController.m
  • In between the parentheses in @interface ViewController () add CameraDelegateMethods
  • Between the openCamera method and @end, add -(BOOL) launchCameraControllerFromViewController: (UIViewController*) controller usingDelegate: (id <UIImagePickerControllerDelegate, UINavigationControllerDelegate>) delegate {}
This is the method we will be using to launch the camera controller
  • In the launchCameraController method, we need to check if there is a camera available for use first, so we add the following lines:
BOOL truefalse = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]; //variable to check whether there is a camera available
//if there is a camera, the delegate passed exists, and the controller passed exists, proceed on, otherwise don't go any further
if (!truefalse || (delegate == nil) || (controller == nil)) {
  NSLog(@"no can do, delegate/camera/view controller doesn't exist!");
  return NO;
}

Now that we've verified that there is a camera, we can proceed launching the camera controller
  • We declare a UIimagePickerController variable and initialize it (UIImagePickerController *cameraController = [[UIImagePickerController alloc] init];)
  • Then we set its sourceType to UIImagePickerControllerSourceTypeCamera
  • set its media types to [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera]
  • set allowsEditing to NO
  • then set the delegate to delegate
In case your eyes glazed over, or you don't know how to that, here's the code:

cameraController.sourceType = UIImagePickerControllerSourceTypeCamera;
cameraController.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
cameraController.allowsEditing = NO;
cameraController.delegate = delegate;
  • after all that, we launch it by calling [controller presentModalViewController:cameraController animated:YES];
  • now, go back to the openCamera method and add [self launchCameraControllerFromViewController:self usingDelegate:self]; //lauch the camera controller

Delegate Methods

Screen Shot 2013-01-04 at 8.55.23 PM.png
Now that we've launched the camera controller and declared ViewController as its delegate, we need to use our delegate methods.

First is to handle the user hitting the cancel button.
  • Add the method - (void) imagePickerControllerDidCancel: (UIImagePickerController *) picker {}
  • The only line you need to add in this method is:
[picker dismissModalViewControllerAnimated:YES]; //dismisses the camera controller

Second is to handle saving of pictures and videos
  • Add the method - (void) imagePickerController: (UIImagePickerController*) picker didFinishPickingMediaWithInfo:(NSDictionary *)info
  • first we declare our variables:
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *originalImage, *editedImage, *imageToSave;
  • Then we go to our process for saving an image
// Process for saving an image
    if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0)
  == kCFCompareEqualTo) {//if it's an image
 
        editedImage = (UIImage *) [info objectForKey:
           UIImagePickerControllerEditedImage]; //Assign the edited image to editedImage
        originalImage = (UIImage *) [info objectForKey:
          UIImagePickerControllerOriginalImage]; //Assign the original image to originalImage
  //Check to see if there was indeed an edited image, if so use that, otherwise use the original
        if (editedImage) {
            imageToSave = editedImage;
        } else {
            imageToSave = originalImage;
        }
 
  // Save the image to the Camera Roll
        UIImageWriteToSavedPhotosAlbum (imageToSave, nil, nil , nil);
    }
  • Then for video:
// Process for saving a video
    if (CFStringCompare ((CFStringRef) mediaType, kUTTypeMovie, 0)
  == kCFCompareEqualTo) {//if it's a video
  //define the movie
        NSString *moviePath = [[info objectForKey:
        UIImagePickerControllerMediaURL] path];
  //if possible, save in the camera roll
        if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum (moviePath)) {
            UISaveVideoAtPathToSavedPhotosAlbum (
             moviePath, nil, nil, nil);
        }
    }
  • Then to clean up, we dismiss the controller and change the image view to the picture we just took (if it was a picture):
[picker dismissModalViewControllerAnimated: YES]; //Dismiss the controller
[self.imageView setImage:imageToSave]; //Assign the picture to the image view

Launch and Play

iPadInitial.png
iPadSecond.png
iPadThird.png
iPadFinal.png
If you followed all the instructions, you should now have a fully functioning app.
  • Plug in your device, upload the app, and take a picture.
  • After you save it, note that the white background became that picture.
  • Now go over to your camera roll and note that that picture was save there.