Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

SWIFT: PHPicker – Best way to access photo and video data from Photos

SWIFT: PHPicker – Best way to access Photo and video data from Photos

Importing photos and videos as media is a common feature used by many iOS applications. There are two methods for doing that: either by utilizing a given framework or by implementing a custom picker. The second method is significantly more complicated. Here, we focus on the first option. iOS 14 introduced a brand new photo picker controller, the PHPicker API. 

Up until iOS 13, the available photo picker was UIImagePickerController, a familiar view controller that made its debut many years back. UIImagePickerController has provided dual functionality; photos and videos are imported to the app. The other captures new media using a camera from the iPhone or iPad.

However, this controller has two disadvantages; the first is that it provides a relatively limited environment to pick media items. Users can select one photo or video at each time only and there is no option to search amongst photos or videos stored in the user’s library. The second downside is that developers are required to ask users for their consent, and then add new entries in the app’s Info.plist file with a description of the intended use.

PHPicker changes all that and makes importing photos and videos faster and more effortless. First of all, its most fantastic feature is that it allows single and multiple item selection, which users greatly appreciate. In addition, it offers a search feature in a picker similar to the Photos app, so users see a familiar UI; they already know what to do when such a picker is presented to them.

What is PHPicker?

PHPicker is the system-provided Picker that allows you to access photos and videos from the user’s photo library. It has built-in support for search, just like the photos app. It supports fluid zooming in the grid, and a highly requested feature, multi-select for third-party apps, where users can even review their selection.

Figure 1: PHPicker

Features

  • All-new design
  • A new easy to use API
  • Supports multi-selection
  • Can specify the selectable types

Another significant feature is that PHPicker has privacy built-in by default. It does not need direct access to the photos library to show the picker, and the picker will not prompt for access on behalf of the app. It provides the user-selected photos and videos only, which indicates the clear users’ intent of sharing the assets with your app. 

Figure 2: PHPicker out of process working flow

PHPicker runs processes outside of the app even though it looks like PHPicker runs inside the app. The app cannot access the picker directly and cannot even take screenshots of the picker content. Only photos and videos selected by the user are passed back to the host app (Figure 2). 

NEW API

Figure 3: PHPicker API components

PHPickerConfiguration is used to specify the multi-select limit or with an optional PHPickerFilter, to choose the selectable types. The configuration is passed to PHPickerController during its initialization. Set a delegate to implement it in your app to get a response. Once a user confirms the selection, the picker creates PHPickerResult objects then passes them back to the delegate

Let’s have a look at how it works in code.

var configuration = PHPickerConfiguration()
// "unlimited" selection by specifying 0, default is 1
configuration.selectionLimit = 0

// Only show images (including Live Photos)
configuration.filter = .images
// Only videos or Live Photos (for their video complement), but no images
configuration.filter = .any(of: [.videos, .livePhotos])

As I already mentioned, you can use a configuration to specify the selection limit and filter the visible item types. 

First, we initialize the configuration. 

var configuration = PHPickerConfiguration()

You can specify a selection limit for the picker. The default limit is one, and to allow unlimited selection, set the selection limit to zero. 

// "unlimited" selection by specifying 0, default is 1
configuration.selectionLimit = 0

You can then specify a filter to restrict the types of selected items. For example, use the images filter if you only want to show images, including live photos. 

// Only show images (including Live Photos)
configuration.filter = .images

You can even combine photos. The picker will only show videos and live photos in this example but no images. 

// Only videos or Live Photos (for their video complement), but no images
configuration.filter = .any(of: [.videos, .livePhotos])

The PHPickerViewController is initialized with the configuration. First, let’s create a configuration and then pass the configuration to the picker ViewController during initialization. Assign a delegate to the picker and present the picker.

let configuration = PHPickerConfiguration()

// Initialize picker view controller with a configuration
let picker = PHPickerViewController(configuration: configuration)

// Assign a delegate
picker.delegate = self

// The client is responsible for presentation and dismissal
present(picker, animated: true)

Please note that your app is responsible for the presentation and dismissal of the picker. The picker does not manage the display itself. 

func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
// The client is responsible for presentation and dismissal
picker.dismiss (animated: true)

// Get the first item provider from the results
let itemProvider = results.first?.itemProvider

// Access the UIImage representation for the result
If let itemProvider = itemProvider, itemProvider.canLoadObject(ofClass: UIImage.self) {
        itemProvider.loadObject(ofClass: UIImage.self) {  image, error in
            if let image = image {
              // Do something with the UIImage
             }        
    }
}

Once the user confirms this selection, the delegate method will be called. So first, let’s dismiss the picker. Then you can ask the result object for an NSItemProvider. The itemProvider presents multiple different representations of the selected item. First, ask the provider if it can load the type you want to load and then actually load it. Then your app can do something with the image.

Remember that the item provider API is async, and you should handle any errors occurring here. 

Short full example here:

struct ContentView: View {
    @State private var isPresented: Bool = false
    var body: some View {
        Button("Present Picker") {
            isPresented.toggle()
        }.sheet(isPresented: $isPresented) {
            let configuration = PHPickerConfiguration(photoLibrary: PHPhotoLibrary.shared())
            PhotoPicker(configuration: configuration, isPresented: $isPresented)
        }
    }
}

struct PhotoPicker: UIViewControllerRepresentable {
    let configuration: PHPickerConfiguration
    @Binding var isPresented: Bool
    func makeUIViewController(context: Context) -> PHPickerViewController {
        let controller = PHPickerViewController(configuration: configuration)
        controller.delegate = context.coordinator
        return controller
    }
    func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) { }
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    // Use a Coordinator to act as your PHPickerViewControllerDelegate
    class Coordinator: PHPickerViewControllerDelegate {
      
        private let parent: PhotoPicker
        
        init(_ parent: PhotoPicker) {
            self.parent = parent
        }
        func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
            print(results)
            // Set isPresented to false because picking has finished.
            parent.isPresented = false /        
        }
    }
}

For more details, check out the Apple documentation here: https://developer.apple.com/documentation/photokit/phpickerviewcontroller#topics

The post SWIFT: PHPicker – Best way to access photo and video data from Photos appeared first on RobustTechHouse - Mobile App Development Singapore.



This post first appeared on Mobile App Development Singapore | IOS &, please read the originial post: here

Share the post

SWIFT: PHPicker – Best way to access photo and video data from Photos

×

Subscribe to Mobile App Development Singapore | Ios &

Get updates delivered right to your inbox!

Thank you for your subscription

×