iOS - Choosing Image From Photo Library In Swift

Introduction

This article will demonstrate a simple demo to explain how to display an image chosen from the photo library on screen using Swift Programming Language.

Prerequisites

  1. MacOS
  2. XCode

Let's start by creating a new project on XCode. To create a new project, open XCode -> File -> New Project -> iOS -> App.

Enter the Product Name, select Interface as Storyboard, and choose the Language as Swift.

Save the project to a desired location.

New Project

We will start by asking the user's permission to access his photo library. For this, we will be adding the permissions in the Info.plist file.

Go to Info. plist the file and add a new row. Type 'NSPhotoLibraryUsageDescription' or search for 'Privacy - Photo Library Usage Description' in the Key column. In the Value column, give your desired message.

Privacy

Similarly, if want to request permission to access the user's camera, type 'NSCameraUsageDescription' or search 'Privacy - Camera Usage Description' in the Key column.

Now, let's create a UIImageView, where we will be uploading the image that we select from the photo library.

In this demo, I have created a circular image with an Edit button. On click of the Edit Button, the photo library will be displayed and once we select the image, the selected image will be displayed on the image view.

In this demo, I created the UI programmatically. You can make use of a storyboard as well.

To create the UIImageView, create a variable as shown below. I have named my UIImageView as profileImage.

var profileImage: UIImageView = {
        let imageView = UIImageView(frame: CGRectMake(0, 0, 150, 150))
        return imageView
    }()

In the above code, we have used CGRectMake which will return a rectangle with the defined values.

For the UIImageView to be displayed, we need to add it inside the view. Add the following line inside the viewDidLoad() function.

view.addSubview(profileImage)

Now, we will position the UIImageView as we need. Add the following code to position the UIImageView as well as to set its width and height.

profileImage.translatesAutoresizingMaskIntoConstraints = false
// Positioning the imageview
profileImage.widthAnchor.constraint(equalToConstant: 150).isActive = true
profileImage.heightAnchor.constraint(equalToConstant: 150).isActive = true
profileImage.topAnchor.constraint(equalTo: view.topAnchor, constant: 150).isActive = true
profileImage.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

Next, we will be customizing the UIImageView as per our needs. I want my image view to be circular. So, I'm adding the properties like cornerRadius and clipToBounds.

Note. To make the image view circular, the width and height of the image view should be equal.

Also, I want a black border around my UIImageView. For that, we will be providing borderWidth and borderColor.

// customising imageview
profileImage.layer.borderColor = UIColor.black.cgColor
profileImage.layer.borderWidth = 1
profileImage.image = profileImage.image?.withRenderingMode(.alwaysTemplate)
profileImage.layer.cornerRadius = profileImage.frame.size.height / 2
profileImage.clipsToBounds = true

Now let's create an Edit button.

var editButton: UIButton = {
        let button = UIButton()
        button.setTitle("Edit", for: .normal)
        button.setTitleColor(.black, for: .normal)
        return button
    }()

We need to add the Edit button inside the view to display it on the screen. Add the following line inside the viewDidLoad() function.

view.addSubview(editButton)

Next, we will position the button just below the UIImageView. Paste the following code inside the viewDidLoad() function.

// Positioning the Edit Button.
editButton.translatesAutoresizingMaskIntoConstraints = false
editButton.widthAnchor.constraint(equalToConstant: 150).isActive = true
editButton.heightAnchor.constraint(equalToConstant: 30).isActive = true
editButton.topAnchor.constraint(equalTo: profileImage.bottomAnchor, constant: 5.0).isActive = true
editButton.centerXAnchor.constraint(equalTo: profileImage.centerXAnchor).isActive = true

Run the app and check if the UI is created as desired.

iPhone 14 Pro

The next step would be to open the photo library by clicking of Edit button. So, let's create a function that will be called on click of the Edit button.

@objc func editButtonTapped() {
        let imagePicker = UIImagePickerController()
        imagePicker.sourceType = .photoLibrary
        imagePicker.delegate = self
        self.present(imagePicker, animated: true, completion: nil)
    }

In the editButtonTapped function, we have defined UIImagePickerController. UIImagePickerController is responsible for taking pictures, recording movies, and choosing items from the user’s media library.

We have chosen sourceType as .photoLibrary since we have to choose an image from the photo library. If you want to open the camera, use sourceType as .camera.

Also, make sure to addUIImagePickerControllerDelegate andUINavigationControllerDelegate to the ViewController class.

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate

The next step to make the image picker work is to call the below function:

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

The above function is responsible for informing the delegate that the user has selected an image or a video.

Also, you can see we are assigning the selected image to our UIImageView i.e. profileImage.

info[.originalImage] will return the original, uncropped image selected by the user.

So, the last thing that we would be doing is to call the editButtonTapped function on click of the Edit button. Paste the below line in the viewDidLoad() function.

// To call the 'editButtonTapped'  function on click of Edit Button.
editButton.addTarget(self, action: #selector(editButtonTapped), for: .touchUpInside)

And we are done! Run the project and see the output.

iPhone 14 Pro(2)

iPhone 14 Pro(3)


Similar Articles