UIImagePickerController in Swift with Firebase. Cheat Sheet.

This blog post is more of a cheat sheet type on how to use UIImagePickerController in Swift with Firebase to upload a user profile image to Google cloud. I am also going to include here a video demonstration taken from my video course “Firebase and Swift: Practical examples“. This video will demonstrate the use of the below code when it was already added to a View Controller.

Whenever you need to look up a Swift code example on how to use UIImagePickerController, you can always come here and search SwiftDeveloperBlog by a keyword to find one of this kind of cheat sheets, copy and paste code snippet to your project and continue working on it.

UIImagePickerControllerDelegate and UINavigationControllerDelegate

To be able to use a UIImagePickerController in your Swift class you will need to make your ViewController conform to a couple of delegates:

  • UIImagePickerControllerDelegate
  • UINavigationControllerDelegate
class MainPageViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate
{

  // other code
  override func viewDidLoad() {
    super.viewDidLoad()
  }
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
  }

}

Creating UIImagePickerController

I usually create an present the UIImagePickerController to the user when they tap on a button. So below is an example of the function in Swift that:

  • Creates a new UIImagePickerController,
  • Sets the sourceType to UIImagePickerControllerSourceType.photoLibrary which means that users will need to pick their photo from a photo library on their phone rather than by taking a new picture. To make UIImagePickerController work with a Camera instead, set UIImagePickerControllerSourceType.camera as a sourceType.
  • And presents the UIImagePickerController to a user

Use Photo Library

@IBAction func setProfileImageButtonTapped(_ sender: Any) {
    let profileImagePicker = UIImagePickerController()
    profileImagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
    profileImagePicker.mediaTypes = [kUTTypeImage as String]
    profileImagePicker.delegate = self
    present(profileImagePicker, animated: true, completion: nil)
}

Use Camera

@IBAction func setProfileImageButtonTapped(_ sender: Any) {

       let profileImagePicker = UIImagePickerController()
       profileImagePicker.allowsEditing = false
       profileImagePicker.sourceType = UIImagePickerControllerSourceType.camera
       profileImagePicker.cameraCaptureMode = .photo
       profileImagePicker.modalPresentationStyle = .fullScreen

       present(profileImagePicker, animated: true, completion: nil)
   }

Getting Image Data with the didFinishPickingMediaWithInfo

When the user selects their photo the below function will be called which will get the image data and pass it on to an image upload function.

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
    if let profileImage = info[UIImagePickerControllerOriginalImage] as? UIImage, let optimizedImageData = UIImageJPEGRepresentation(profileImage, 0.6)
    {
        // upload image from here
        uploadProfileImage(imageData: optimizedImageData)
    }
    picker.dismiss(animated: true, completion:nil)
}

Getting image as JPEG

Please note the use of UIImageJPEGRepresentation in the above function.

UIImageJPEGRepresentation(profileImage, 0.6)

the above line of code when executed will get a JPEG representation of your image and will optimize the quality of an image from 100% to 60%. For example, for the highest quality of image use 1 and for 50% of image quality use 0.5.

Getting image as PNG

If you need the PNG representation of this image use UIImagePNGRepresentation instead:

UIImagePNGRepresentation(profileImage, 0.6)

Handle the Cancel Button with imagePickerControllerDidCancel

When the user taps on the Cancel button to cancel and to dismiss the image picker the imagePickerControllerDidCancel function will be called and we can use it to dismiss the presenter to user image picker.

func imagePickerControllerDidCancel(_ picker: UIImagePickerController)
{
    picker.dismiss(animated: true, completion:nil)
}

Upload image to Firebase

You can use the below function to upload an image picked up by UIImagePickerController to a Firebase Cloud storage.

To be able to use the Firebase Cloud Storage and the below code example you will need to import into your View Controller the following library:

import Firebase

and add(using CocoaPods) the following dependencies to your Xcode project:

pod 'Firebase/Core'
pod 'Firebase/Auth'
pod 'Firebase/Storage'

Upload image function

func uploadProfileImage(imageData: Data)
    {
        let activityIndicator = UIActivityIndicatorView.init(activityIndicatorStyle: .gray)
        activityIndicator.startAnimating()
        activityIndicator.center = self.view.center
        self.view.addSubview(activityIndicator)
        
        
        let storageReference = Storage.storage().reference()
        let currentUser = Auth.auth().currentUser
        let profileImageRef = storageReference.child("users").child(currentUser!.uid).child("\(currentUser!.uid)-profileImage.jpg")
        
        let uploadMetaData = StorageMetadata()
        uploadMetaData.contentType = "image/jpeg"
        
        profileImageRef.putData(imageData, metadata: uploadMetaData) { (uploadedImageMeta, error) in
           
            activityIndicator.stopAnimating()
            activityIndicator.removeFromSuperview()
            
            if error != nil
            {
                print("Error took place \(String(describing: error?.localizedDescription))")
                return
            } else {
                
                self.userProfileImageView.image = UIImage(data: imageData)
                
                print("Meta data of uploaded image \(String(describing: uploadedImageMeta))")
            }
        }
    }

Video Demonstration

The below video is taken from my video course called “Firebase and Swift: Practical examples“. This video demonstrates only the use of the above-mentioned code snippets. But if you check out the video course you will find step-by-step instructions on how the Image upload and the image display features are put together from the vebeginninging.

I hope this little cheat sheet will be of some value to you. If you are interested to learn more about Firebase and Swift, please check the list of video courses below. And hopefully one of them will be what you were looking for.