Bird
Raised Fist0
iOS Swiftmobile~5 mins

Camera and photo library in iOS Swift

Choose your learning style10 modes available
Introduction

Using the camera and photo library lets users take pictures or pick photos from their device. This makes apps more interactive and personal.

When you want users to take a new photo inside your app, like for a profile picture.
When you want users to select an existing photo from their gallery.
When building a social app that shares photos.
When creating a document scanner app that uses the camera.
When allowing users to customize content with their own images.
Syntax
iOS Swift
import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
  func openCamera() {
    guard UIImagePickerController.isSourceTypeAvailable(.camera) else { return }
    let picker = UIImagePickerController()
    picker.sourceType = .camera
    picker.delegate = self
    present(picker, animated: true)
  }

  func openPhotoLibrary() {
    let picker = UIImagePickerController()
    picker.sourceType = .photoLibrary
    picker.delegate = self
    present(picker, animated: true)
  }

  func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let image = info[.originalImage] as? UIImage {
      // use the selected image
    }
    picker.dismiss(animated: true)
  }
}

Use UIImagePickerController to access camera or photo library.

Set sourceType to .camera or .photoLibrary depending on what you want.

Examples
This opens the camera for the user to take a new photo.
iOS Swift
let picker = UIImagePickerController()
picker.sourceType = .camera
present(picker, animated: true)
This opens the photo library so the user can pick an existing photo.
iOS Swift
let picker = UIImagePickerController()
picker.sourceType = .photoLibrary
present(picker, animated: true)
Sample App

This app shows two buttons: one to open the camera and one to open the photo library. When the user picks or takes a photo, it appears on the screen.

iOS Swift
import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
  let imageView = UIImageView()
  let cameraButton = UIButton(type: .system)
  let libraryButton = UIButton(type: .system)

  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white

    imageView.frame = CGRect(x: 50, y: 100, width: 300, height: 300)
    imageView.contentMode = .scaleAspectFit
    view.addSubview(imageView)

    cameraButton.frame = CGRect(x: 50, y: 420, width: 140, height: 50)
    cameraButton.setTitle("Open Camera", for: .normal)
    cameraButton.addTarget(self, action: #selector(openCamera), for: .touchUpInside)
    view.addSubview(cameraButton)

    libraryButton.frame = CGRect(x: 210, y: 420, width: 140, height: 50)
    libraryButton.setTitle("Open Library", for: .normal)
    libraryButton.addTarget(self, action: #selector(openPhotoLibrary), for: .touchUpInside)
    view.addSubview(libraryButton)
  }

  @objc func openCamera() {
    guard UIImagePickerController.isSourceTypeAvailable(.camera) else { return }
    let picker = UIImagePickerController()
    picker.sourceType = .camera
    picker.delegate = self
    present(picker, animated: true)
  }

  @objc func openPhotoLibrary() {
    let picker = UIImagePickerController()
    picker.sourceType = .photoLibrary
    picker.delegate = self
    present(picker, animated: true)
  }

  func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let image = info[.originalImage] as? UIImage {
      imageView.image = image
    }
    picker.dismiss(animated: true)
  }

  func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    picker.dismiss(animated: true)
  }
}
OutputSuccess
Important Notes

Always check if the camera is available before opening it to avoid crashes.

Remember to add usage descriptions in your app's Info.plist for camera and photo library access.

Handle user denial of permissions gracefully.

Summary

Use UIImagePickerController to let users take or pick photos.

Set sourceType to .camera or .photoLibrary accordingly.

Implement delegate methods to get the selected or taken image.

Practice

(1/5)
1. What is the purpose of setting sourceType to .camera in UIImagePickerController?
easy
A. To select an existing photo from the photo library
B. To record a video using the device camera
C. To allow the user to take a new photo using the device camera
D. To open the device settings

Solution

  1. Step 1: Understand sourceType usage

    The sourceType property of UIImagePickerController defines where the image will come from.
  2. Step 2: Identify the effect of .camera

    Setting sourceType to .camera opens the device camera to take a new photo.
  3. Final Answer:

    To allow the user to take a new photo using the device camera -> Option C
  4. Quick Check:

    sourceType = .camera means take new photo [OK]
Hint: Camera sourceType means take a new photo [OK]
Common Mistakes:
  • Confusing .camera with .photoLibrary
  • Thinking .camera records video by default
  • Assuming .camera opens settings
2. Which of the following is the correct way to declare a UIImagePickerController and set its delegate in Swift?
easy
A. var picker = UIImagePickerController() picker.delegate = self()
B. let picker = UIImagePickerController() picker.delegate = self
C. let picker = UIImagePickerController picker.delegate = self()
D. var picker = UIImagePickerController picker.delegate = self

Solution

  1. Step 1: Correct initialization syntax

    In Swift, UIImagePickerController() requires parentheses to create an instance.
  2. Step 2: Assign delegate properly

    The delegate is assigned as self without parentheses because it is a property, not a function call.
  3. Final Answer:

    let picker = UIImagePickerController() picker.delegate = self -> Option B
  4. Quick Check:

    Initialize with () and assign delegate without () [OK]
Hint: Use parentheses for init, no parentheses for delegate [OK]
Common Mistakes:
  • Forgetting parentheses when creating UIImagePickerController
  • Using parentheses when assigning delegate
  • Declaring picker without parentheses
3. Given the following code snippet, what will be printed when a user selects a photo from the library?
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let image = info[.originalImage] as? UIImage {
        print("Image selected")
    } else {
        print("No image found")
    }
}
medium
A. Nothing is printed
B. No image found
C. Compilation error
D. Image selected

Solution

  1. Step 1: Check the delegate method behavior

    The method imagePickerController(_:didFinishPickingMediaWithInfo:) is called after user picks a photo.
  2. Step 2: Understand the info dictionary

    The info dictionary contains the key .originalImage with the selected UIImage if successful.
  3. Final Answer:

    Image selected -> Option D
  4. Quick Check:

    Image exists in info dictionary after selection [OK]
Hint: If image exists in info, print "Image selected" [OK]
Common Mistakes:
  • Assuming image is nil after selection
  • Confusing delegate method names
  • Not casting info dictionary value properly
4. What is the error in the following Swift code that prevents the image picker from working correctly?
let picker = UIImagePickerController()
picker.sourceType = .camera
picker.delegate = self
present(picker, animated: true)
medium
A. Missing UIImagePickerControllerDelegate and UINavigationControllerDelegate conformance
B. Incorrect sourceType value
C. Delegate should be assigned after presenting picker
D. Cannot present picker without a navigation controller

Solution

  1. Step 1: Check delegate conformance requirements

    To use UIImagePickerController delegate methods, the class must conform to UIImagePickerControllerDelegate and UINavigationControllerDelegate.
  2. Step 2: Identify missing conformance

    If the class does not conform, delegate methods won't be called and picker won't work properly.
  3. Final Answer:

    Missing UIImagePickerControllerDelegate and UINavigationControllerDelegate conformance -> Option A
  4. Quick Check:

    Delegate protocols must be adopted for picker to work [OK]
Hint: Always conform to both delegate protocols [OK]
Common Mistakes:
  • Forgetting to add delegate protocols to class
  • Assigning delegate after presenting picker
  • Using wrong sourceType value
5. You want to allow users to either take a new photo or pick one from their library. Which approach correctly handles both options in Swift?
hard
A. Set sourceType dynamically based on user choice, then present a single UIImagePickerController
B. Use sourceType = .savedPhotosAlbum to cover both camera and library
C. Create two UIImagePickerController instances, one with .camera and one with .photoLibrary, and present both simultaneously
D. Use UIImagePickerController only for camera and a custom UI for photo library

Solution

  1. Step 1: Understand sourceType flexibility

    A single UIImagePickerController can have its sourceType set to either .camera or .photoLibrary before presenting.
  2. Step 2: Handle user choice before presenting picker

    Based on user selection, set the sourceType dynamically and present the picker once.
  3. Final Answer:

    Set sourceType dynamically based on user choice, then present a single UIImagePickerController -> Option A
  4. Quick Check:

    One picker, sourceType changes per user choice [OK]
Hint: Use one picker, change sourceType before presenting [OK]
Common Mistakes:
  • Trying to present two pickers at once
  • Using savedPhotosAlbum to cover camera
  • Mixing custom UI unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard