PHPicker delegate error: PHPickerViewControllerDelegate doesn't respond to picker:didFinishPicking

1.7k Views Asked by At

In WWDC20 apple introduced PHPicker, the replacement for UIImagePickerController.

I have a wrapper NSObject class witch handles all the configuration and presentation of image picker controller, now I'm replacing the implementation to support iOS14.

Even if I set the delegate to be self I get the error:

[Picker] PHPickerViewControllerDelegate doesn't respond to picker:didFinishPicking:

I think it checks on the parent view controller, that indeed it's not implementing the delegate methods but the wrapper does.

Here is my example code:

import Foundation
import PhotosUI

class myPicker: PHPickerViewControllerDelegate{
    
    func openFrom(parent:UIViewController!) {
        var config:PHPickerConfiguration! = PHPickerConfiguration()
        config.selectionLimit = 1
        config.filter = nil
        
        let pickerViewController:PHPickerViewController! = PHPickerViewController(configuration:config)
        pickerViewController.delegate = self //<---
        parent.present(pickerViewController, animated:true, completion:nil)
        
    }
    
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        
        picker.dismiss(animated: true, completion:nil)
        
        for result:PHPickerResult in results {
            let itemProvider:NSItemProvider = result.itemProvider
            print(itemProvider)
        }

// ...do something with images...
    }
}

Using it...

 override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        let mypicker = myPicker()
        mypicker.openFrom(parent: self)
    }

What do you suggest?

2

There are 2 best solutions below

1
On

You need to make "class myPicker" as a singleton class. Because you should make sure delegate not to be nil. Also, you can change this instance = nil in the didFinishPicking method.

0
On

The problem is that Cocoa Objective-C cannot introspect your class. Change

class myPicker: PHPickerViewControllerDelegate

To

class myPicker: NSObject, PHPickerViewControllerDelegate