Design+Code logo

Quick links

Suggested search

Create the ImagePicker

Firstly, you'll need to create the ImagePicker. It's a ViewController that will enable you to show the user's photo library or their camera in order to change their profile picture. We need to add a sourceType to specify if we want to pick from the library or the camera. Also, the selectedImage and the Coordinator will enable us to preview the selected image in the View.

import SwiftUI

struct ImagePicker: UIViewControllerRepresentable {
    @Environment(\.presentationMode) private var presentationMode
    var sourceType: UIImagePickerController.SourceType = .photoLibrary
    @Binding var selectedImage: UIImage

    func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {

        let imagePicker = UIImagePickerController()
        imagePicker.allowsEditing = false
        imagePicker.sourceType = sourceType
        imagePicker.delegate = context.coordinator

        return imagePicker
    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {

    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

        var parent: ImagePicker

        init(_ parent: ImagePicker) {
            self.parent = parent
        }

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

            if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
                parent.selectedImage = image
            }

            parent.presentationMode.wrappedValue.dismiss()
        }

    }
}

Note: By default, the ImagePicker will only enable the user to choose from pictures or take a picture - videos are not included.

Add states

In your View, add the following states. The image variable is where we'll save the selected image and pass it to our ImagePicker. The second state, showSheet, will be toggled to show the ImagePicker as a sheet, on top of your View.

@State private var image = UIImage()
@State private var showSheet = false

Create a button

Create the button on which the user will tap to show the ImagePicker.

Text("Change photo")
		.font(.headline)
		.frame(maxWidth: .infinity)
		.frame(height: 50)
		.background(LinearGradient(gradient: Gradient(colors: [Color(#colorLiteral(red: 0.262745098, green: 0.0862745098, blue: 0.8588235294, alpha: 1)), Color(#colorLiteral(red: 0.5647058824, green: 0.462745098, blue: 0.9058823529, alpha: 1))]), startPoint: .top, endPoint: .bottom))
		.cornerRadius(16)
		.foregroundColor(.white)

Create an Image

Add an Image to your View so the user can preview the image they just selected.

Image(uiImage: self.image)
		.resizable()
		.cornerRadius(50)
		.padding(.all, 4)
		.frame(width: 100, height: 100)
		.background(Color.black.opacity(0.2))
		.aspectRatio(contentMode: .fill)
		.clipShape(Circle())
		.padding(8)

If no image is selected, by default, the user will see a grey circle.

Screen Shot 2021-03-02 at 9.57.23 AM

Toggle the state

OnTapGesture of the Button, change the showSheet state to true so we can show the sheet by listening to this state.

.onTapGesture {
	showSheet = true
}

Add the sheet modifier

Add the sheet modifier that will listen to the showSheet state and show the user's photo library when showSheet is set to true.

.sheet(isPresented: $showSheet) {
		ImagePicker(sourceType: .photoLibrary, selectedImage: self.$image)
}

Screen Shot 2021-03-02 at 9.56.52 AM

Take a photo from the camera

If you wish to take photo from camera, simply change the sourceType to .camera.

ImagePicker(sourceType: .camera, selectedImage: self.$image)

Don't forget to add in your Info.plist a new key/value pair to ask the user permission to access their camera. Under the iOS folder, click on Info.plist. Add a new key, and name it Privacy - Camera Usage Description. Under the value column, specify why you need to use the camera.

Screen Shot 2021-03-02 at 10.00.01 AM

Note: It's not possible to test the camera on the Simulator. You'll need to connect your device to your Mac in order to test it.

Final code

The final code for the View is:

@State private var image = UIImage()
@State private var showSheet = false

var body: some View {
		HStack {
				Image(uiImage: self.image)
		      .resizable()
		      .cornerRadius(50)
		      .frame(width: 100, height: 100)
		      .background(Color.black.opacity(0.2))
		      .aspectRatio(contentMode: .fill)
		      .clipShape(Circle())

     Text("Change photo")
         .font(.headline)
         .frame(maxWidth: .infinity)
         .frame(height: 50)
         .background(LinearGradient(gradient: Gradient(colors: [Color(#colorLiteral(red: 0.262745098, green: 0.0862745098, blue: 0.8588235294, alpha: 1)), Color(#colorLiteral(red: 0.5647058824, green: 0.462745098, blue: 0.9058823529, alpha: 1))]), startPoint: .top, endPoint: .bottom))
         .cornerRadius(16)
         .foregroundColor(.white)
		     .padding(.horizontal, 20)
		     .onTapGesture {
		       showSheet = true
		     }
		}
    .padding(.horizontal, 20)
    .sheet(isPresented: $showSheet) {
				// Pick an image from the photo library:
		    ImagePicker(sourceType: .photoLibrary, selectedImage: self.$image)

				//  If you wish to take a photo from camera instead:
				// ImagePicker(sourceType: .camera, selectedImage: self.$image)
		}
}

Learn with videos and source files. Available to Pro subscribers only.

Purchase includes access to 50+ courses, 320+ premium tutorials, 300+ hours of videos, source files and certificates.

BACK TO

App Review

READ NEXT

Compress a UIImage

Templates and source code

Download source files

Download the videos and assets to refer and learn offline without interuption.

check

Design template

check

Source code for all sections

check

Video files, ePub and subtitles

Browse all downloads

1

Firebase Auth

How to install Firebase authentification to your Xcode project

8:18

2

Read from Firestore

Install Cloud Firestore in your application to fetch and read data from a collection

8:01

3

Write to Firestore

Save the data users input in your application in a Firestore collection

5:35

4

Join an Array of Strings

Turn your array into a serialized String

3:33

5

Data from JSON

Load data from a JSON file into your SwiftUI application

5:08

6

HTTP Request

Create an HTTP Get Request to fetch data from an API

6:31

7

WKWebView

Integrate an HTML page into your SwiftUI application using WKWebView and by converting Markdown into HTML

5:25

8

Code Highlighting in a WebView

Use Highlight.js to convert your code blocks into beautiful highlighted code in a WebView

5:11

9

Test for Production in the Simulator

Build your app on Release scheme to test for production

1:43

10

Debug Performance in a WebView

Enable Safari's WebInspector to debug the performance of a WebView in your application

1:57

11

Debug a Crash Log

Learn how to debug a crash log from App Store Connect in Xcode

2:22

12

Simulate a Bad Network

Test your SwiftUI application by simulating a bad network connection with Network Link Conditionner

2:11

13

Archive a Build in Xcode

Archive a build for beta testing or to release in the App Store

1:28

14

Apollo GraphQL Part I

Install Apollo GraphQL in your project to fetch data from an API

6:21

15

Apollo GraphQL Part 2

Make a network call to fetch your data and process it into your own data type

6:43

16

Apollo GraphQL Part 3

Display the data fetched with Apollo GraphQL in your View

5:08

17

Configuration Files in Xcode

Create configuration files and add variables depending on the environment - development or production

4:35

18

App Review

Request an app review from your user for the AppStore

5:43

19

ImagePicker

Create an ImagePicker to choose a photo from the library or take a photo from the camera

5:06

20

Compress a UIImage

Compress a UIImage by converting it to JPEG, reducing its size and quality

3:32

21

Firebase Storage

Upload, delete and list files in Firebase Storage

11:11

22

Search Feature

Implement a search feature to filter through your content in your SwiftUI application

9:13

23

Push Notifications Part 1

Set up Firebase Cloud Messaging as a provider server to send push notifications to your users

5:59

24

Push Notifications Part 2

Create an AppDelegate to ask permission to send push notifications using Apple Push Notifications service and Firebase Cloud Messaging

6:30

25

Push Notifications Part 3

Tie everything together and test your push notifications feature in production

6:13

26

Network Connection

Verify the network connection of your user to perform tasks depending on their network's reachability

6:49

27

Download Files Locally Part 1

Download videos and files locally so users can watch them offline

6:05

28

Download Files Locally Part 2

Learn how to use the DownloadManager class in your views for offline video viewing

6:02

29

Offline Data with Realm

Save your SwiftUI data into a Realm so users can access them offline

10:20

30

HTTP Request with Async Await

Create an HTTP get request function using async await

6:11

31

Xcode Cloud

Automate workflows with Xcode Cloud

9:23

32

SceneStorage and TabView

Use @SceneStorage with TabView for better user experience on iPad

3:52

33

Network Connection Observer

Observe the network connection state using NWPathMonitor

4:37

34

Apollo GraphQL Caching

Cache data for offline availability with Apollo GraphQL

9:42

35

Create a model from an API response

Learn how to create a SwiftUI model out of the response body of an API

5:37

36

Multiple type variables in Swift

Make your models conform to the same protocol to create multiple type variables

4:23

37

Parsing Data with SwiftyJSON

Make API calls and easily parse data with this JSON package

9:36

38

ShazamKit

Build a simple Shazam clone and perform music recognition

12:38

39

Firebase Remote Config

Deliver changes to your app on the fly remotely

9:05