An Example iOS 7 iPhone Camera Application

From Techotopia
Jump to: navigation, search
PreviousTable of ContentsNext
Accessing the iOS 7 Camera and Photo LibraryVideo Playback from within an iOS 7 Application


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book


In the chapter entitled Accessing the iPhone Camera and Photo Library we looked in some detail at the steps necessary to provide access to the iOS camera and photo libraries in an iOS 7 application. The purpose of this chapter is to build on this knowledge by working through an example iPhone application designed to access the device’s camera and photo libraries.


Contents


An Overview of the Application

The application user interface for this example will consist of an image view and a toolbar containing two buttons. When touched by the user, the first button will display the camera to the user and allow a photograph to be taken which will subsequently be displayed in the image view. The second button will provide access to the camera roll where the user may select an existing photo image. In the case of a new image taken with the camera, this will be saved to the camera roll.

Since we will be covering the playback of video in the next chapter (Video Playback from within an iOS 7 Application) the camera roll and camera will be restricted to still images in this example. The addition of video support to this application is left as an exercise for the reader.

Creating the Camera Project

Begin the project by launching Xcode and creating a new iPhone iOS application project named Camera using the Single View Application template.


Designing the User Interface

The next step in this tutorial is to design the user interface. This is a very simple user interface consisting of an image view, a toolbar and two bar button items. Select the Main.storyboard file and drag and drop components from the Library window (View -> Utilities -> Show Object Library) onto the view. Position and size the components and set the text on the bar button items so that the user interface resembles Figure 75-1.

The user interface layout for the iOS 7 camera app

Figure 75-1


In terms of auto layout constraints, begin by selecting the toolbar view and clicking on the Pin menu in the toolbar located in the lower right hand corner of the storyboard canvas and establish spacing constraints to the nearest neighbor for all four sides of the toolbar as illustrated in Figure 75 2. Once configured, click on the Add 4 Constraints button to create the constraints.


Adding auto layout constraints to the toolbar

Figure 75-2


Next, select the Image View object and, once again using the Pin menu, establish nearest neighbor constraints as follows and as illustrated in Figure 75 3:

  • Top Edge – Use standard Value to Top Layout Guide (to access these options, click on the down arrow in the text box containing the space value to display the drop down menu).
  • Right and Left – 20 points spacing to the corresponding edges of the containing view.


Adding auto layout constraints to the image view

Figure 75-3


With the constraints configured, click on the Add 3 Constraints button. Finally, with the Image View still selected, display the Size Inspector panel (View -> Utilities -> Show Size Inspector) and reduce the Vertical Content Compression Resistance Priority value to 100. This will prevent the image view from growing vertically and obscuring the toolbar when displaying large images.

Select the image view object in the view canvas, display the Assistant Editor panel and verify that the editor is displaying the contents of the CameraViewController.h file. Ctrl-click on the image view object and drag to a position just below the @interface line in the Assistant Editor. Release the line, and, in the resulting connection dialog, establish an outlet connection named imageView.

With the Assistant Editor visible, establish action connections for the two buttons to methods named useCamera and useCameraRoll respectively (keeping mind that it may be necessary to click twice on each button to select it since the first click will typically select the toolbar parent object).

Finally, select the CameraViewController.h file and modify it further to add import and delegate protocol declarations together with a boolean property declaration that will be required later in the chapter:

#import <UIKit/UIKit.h>
#import <MobileCoreServices/MobileCoreServices.h>

@interface CameraViewController : UIViewController
<UIImagePickerControllerDelegate,
         UINavigationControllerDelegate>

@property BOOL newMedia;
@property (strong, nonatomic) IBOutlet UIImageView *imageView;
- (IBAction)useCamera:(id)sender;
- (IBAction)useCameraRoll:(id)sender;
@end

Implementing the Action Methods

The useCamera and useCameraRoll action methods now need to be implemented. The useCamera method first needs to check that the device on which the application is running has a camera. It then needs to create a UIImagePickerController instance, assign the cameraViewController as the delegate for the object and define the media source as the camera. Since we do not plan on handling videos the supported media types property is set to images only. Finally, the camera interface will be displayed. The last task is to set the newMedia flag to YES to indicate that the image is new and is not an existing image from the camera roll. Bringing all these requirements together gives us the following useCamera method:

- (void) useCamera:(id)sender
{
    if ([UIImagePickerController isSourceTypeAvailable:
           UIImagePickerControllerSourceTypeCamera])
    {
           UIImagePickerController *imagePicker =
             [[UIImagePickerController alloc] init];
           imagePicker.delegate = self;
           imagePicker.sourceType =
             UIImagePickerControllerSourceTypeCamera;
           imagePicker.mediaTypes = @[(NSString *) kUTTypeImage];
           imagePicker.allowsEditing = NO;
           [self presentViewController:imagePicker
             animated:YES completion:nil];
           _newMedia = YES;
     }
}
.
.
@end

Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book

The useCameraRoll method is remarkably similar to the previous method with the exception that the source of the image is declared to be UIImagePickerControllerSourceTypePhotoLibrary and the newMedia flag is set to NO (since the photo is already in the library we don’t need to save it again):

- (void) useCameraRoll:(id)sender
{
    if ([UIImagePickerController isSourceTypeAvailable:
          UIImagePickerControllerSourceTypeSavedPhotosAlbum])
    {
       UIImagePickerController *imagePicker =
           [[UIImagePickerController alloc] init];
       imagePicker.delegate = self;
       imagePicker.sourceType =
           UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.mediaTypes = @[(NSString *) kUTTypeImage];
       imagePicker.allowsEditing = NO;
       [self presentViewController:imagePicker 
           animated:YES completion:nil];
       _newMedia = NO;
    }
}

Writing the Delegate Methods

As described in Accessing the iPhone Camera and Photo Library, in order to fully implement an instance of the image picker controller delegate protocol it is necessary to implement some delegate methods. The most important method is didFinishPickingMediaWithInfo which is called when the user has finished taking or selecting an image. The code for this method in our example reads as follows:

#pragma mark -
#pragma mark UIImagePickerControllerDelegate

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

   [self dismissViewControllerAnimated:YES completion:nil];

    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        UIImage *image = info[UIImagePickerControllerOriginalImage];

        _imageView.image = image;
        if (_newMedia)
            UIImageWriteToSavedPhotosAlbum(image,
               self,
               @selector(image:finishedSavingWithError:contextInfo:),
               nil);
        }
        else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
        {
                // Code here to support video if enabled
        }
}

-(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];
   }
}

The code in this delegate method dismisses the image picker view and identifies the type of media passed from the image picker controller. If it is an image it is displayed on the view image object of the user interface. If this is a new image it is saved to the camera roll. The finishedSavingWithError method is configured to be called when the save operation is complete. If an error occurred it is reported to the user via an alert box.

It is also necessary to implement the imagePickerControllerDidCancel delegate method which is called if the user cancels the image picker session without taking a picture or making an image selection. In most cases all this method needs to do is dismiss the image picker:

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

Building and Running the Application

In order to experience the full functionality of this application it will be necessary to install it on a physical iPhone or device with a camera. Steps on performing this are covered in Testing Apps on iOS 7 Devices with Xcode 5.

Assuming certificates and provisioning are configured, click on the Run button to launch the application. Once the application loads, select the Camera button to launch the camera interface.


The iOS 7 Camera example app running

Figure 75-4


Once the picture has been taken and selected for use in the application, it will appear in the image view object of our application user interface.

Selecting the Camera Roll button will provide access to the camera roll and photo stream on the device where an image selection can be made:


The iOS 7 Camera Roll Interface

Figure 75-5


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book



PreviousTable of ContentsNext
Accessing the iOS 7 Camera and Photo LibraryVideo Playback from within an iOS 7 Application