Warning: Illegal string offset 'value' in /home/content/44/9038144/html/deegeu/wp-content/themes/Divi/includes/builder/main-modules.php on line 14095

How to access the iOS camera using Swift 2.0

by | Oct 19, 2015




Transcript – How to access the iOS camera using Swift 2.0

Introduction

One of the best features on the iPhone is the camera. In this video I want to share with you how we can add camera functionality to our Swift apps. Coming up next!

This video uses Swift 2.0 and the UIImagePickerController to access the camera. We’re also just looking at taking pictures in this tutorial. We will look at selecting photos from the photo library in another video. Our app will have a button, and image view. When the user presses the button, we’ll launch a controller to take a picture. If the user takes a picture, we’ll display it in the image view.

Steps to access the iOS camera using Swift

Taking pictures from the camera can be summed up in 4 steps. First we need to see if our app has access to the camera. If the user blocks our app from the camera, we can’t take pictures. Second we need to check if the capture mode is available. What we’re doing here is checking to see if we can take pictures, or pictures and video, does the device have a front camera and so on. Third we set some flags, and present the camera view controller to the user. Finally we’ll need to check to see if we got a picture or if the user selected cancel. If we got an image or if the user cancels, we’re done. Let’s get started with the code.

Using the UIImagePickerController

All the code for this tutorial is going in the ViewController, but you probably want a separate class for your camera code. UIImagePickerController is in UIKit. There’s nothing to add to the imports if we’re embedding the image picker in a view controller, however, if we need to add it in another class, UIKit is where it lives. We’ll add one for the entire class. You only need one, and there’s no point in creating one everytime you want to take a picture.

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet weak var currentImage: UIImageView!

    let imagePicker: UIImagePickerController! = UIImagePickerController()

Since everything is starting with a button press, lets add our camera behavior to the button press. We’ll call the action takePicture.

    @IBAction func takePicture(sender: UIButton) {
        if (UIImagePickerController.isSourceTypeAvailable(.Camera)) {
            if UIImagePickerController.availableCaptureModesForCameraDevice(.Rear) != nil {
                imagePicker.allowsEditing = false
                imagePicker.sourceType = .Camera
                imagePicker.cameraCaptureMode = .Photo
                presentViewController(imagePicker, animated: true, completion: {})
            } else {
                postAlert("Rear camera doesn't exist", message: "Application cannot access the camera.")
            }
        } else {
            postAlert("Camera inaccessable", message: "Application cannot access the camera.")
        }
    }

First we need to see if we have access to the camera. We’ll call isSourceTypeAvailable and pass it the enumerated value camera. Our other choices could be the photo library and the saved photo album. Photo library and saved photo album are what you think. This is if you want to pick existing photos instead of taking a picture. We’ll cover that another time. If we get a pass, we’ll continue on. Otherwise we’ll pop up an alert saying we can’t access the camera.

OK. Let’s assume we got a pass. Next we will check if the rear camera is available. If we have a rear camera, it’s really likely we have a front camera too. And it’s very likely we can do video and photos, and pretty likely they have a flash. This all is assuming we’re supporting recent iPhones. If we need to support an older device, we can make other checks like isFlashAvailableForCamera.

We’re not going to check these because the controller won’t make these available as choices if they aren’t available. If we can launch the UIImagePickerController and get access to the rear camera, we’ll get everything else for free. So my code just checks the rear camera. If you need more, you’ll want to command-click on the UIImagePickerController class name to see the other methods available to you.

Alright, we have access to a rear camera, so next we need to set up the UIImagePickerController with the flags we want and launch it. I’m setting allowEditing to false, sourceType to Camera, and cameraCaptureMode to photo. Next we present the controller and we should be able to take pictures!

Need to add UIImagePickerController delegates

Now if you’re typing along at home, you might notice something when we take pictures. The picture isn’t taken. There’s more code we need to add. We need to handle cases where the user took a picture, and the case where the user canceled.

To do this, we need to add two delegates to the UIImagePickerController. These are UIImagePickerControllerDelegate and UINavigationControllerDelegate. We don’t need to add any methods for UINavigationControllerDelegate, but we do need to add a few methods for the UIImagePickerControllerDelegate. These are for the our two camera user events. We’ll set the delegate in the viewDidLoad method.

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        print("Got an image")
        if let pickedImage:UIImage = (info[UIImagePickerControllerOriginalImage]) as? UIImage {
            let selectorToCall = Selector("imageWasSavedSuccessfully:didFinishSavingWithError:context:")
            UIImageWriteToSavedPhotosAlbum(pickedImage, self, selectorToCall, nil)
        }
        imagePicker.dismissViewControllerAnimated(true, completion: {
            // Anything you want to happen when the user saves an image
        })
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        print("User canceled image")
        dismissViewControllerAnimated(true, completion: {
            // Anything you want to happen when the user selects cancel
        })
    }

The first is didFinishPickingMediaWithInfo. In our method, we’ll just save the image to the saved photos album. We’ll also supply a method to let us know the image is saved. When we’re done, we’ll dismiss the view controller. The other method is when the user cancels. In that case, we’ll just dismiss the view controller.

Finally we’ll do something when we’re sure the image was saved. In this case, we’ll display the image in our image view. If we get an error, we’ll print it out.

Final tips using UIImagePickerController

That’s it. Pretty easy, right? The real gotchas when using the UIImagePickerController are forgetting to add the delegates. If we forget to do that, we’ll hit our head on your keyboard for a while trying to figure out why the methods aren’t called. The other thing to look for is making sure you have access to the camera. If our user says no once, we can’t get to the camera. That’s why we want to check for access every time, and if we don’t have access we’ll want to provide a meaningful message telling the user why we really need access to the camera if they want to take pictures with our app.

Thanks again for watching! If you have any questions let me know in the comments. New lessons come out every week, so make sure you subscribe. You don’t want to miss a video! And liking the video lets me know what I’m doing right, so if you liked the video…

And with that, I’ll see you in the next tutorial!







Related Posts

Tools Used

  • Java
  • NetBeans

Media Credits

All media created and owned by DJ Spiess unless listed below.

  • No infringement intended

Music:
Easy Jam by Kevin MacLeod is licensed under a Creative Commons Attribution license (https://creativecommons.org/licenses/by/4.0/)
Source: http://incompetech.com/music/royalty-free/index.html?isrc=USUAN1100245
Artist: http://incompetech.com/

Get the code

The source code for “How to access the iOS camera using Swift 2.0” can be found on Github. If you have Git installed on your system, you can clone the repository by issuing the following command:

 git clone https://github.com/deege/deegeu-swift-camera-basic.git

Go to the Support > Getting the Code page for more help.

If you find any errors in the code, feel free to let me know or issue a pull request in Git.

Don't miss another video!

New videos come out every week. Make sure you subscribe!

Comments

comments

DJ Spiess

DJ Spiess

Your personal instructor

My name is DJ Spiess and I’m a developer with a Masters degree in Computer Science working in Colorado, USA. I primarily work with Java server applications. I started programming as a kid in the 1980s, and I’ve programmed professionally since 1996. My main focus are REST APIs, large-scale data, and mobile development. The last six years I’ve worked on large National Science Foundation projects. You can read more about my development experience on my LinkedIn account.

Pin It on Pinterest

Share This