Image Picker Controller delegate in separate class doesn't work

南楼画角 提交于 2019-12-04 16:02:05

Your issue is one of memory management. Inside your selectImageFromPhotoLibrary you create a local instance of MealPhotoDelegate. At the end of the method, this instance goes out of scope and gets deallocated because there is no strong reference to it. Therefore, the image picker's delegate becomes nil and it doesn't work.

The solution is to make a strong reference to the instance of MealPhotoDelegate. This is easily done using a property in your view controller class.

Add the following property to your view controller class:

var imagePickerDelegate: MealPhotoDelegate?

Then update the line:

let imagePickerDelegate = MealPhotoDelegate()

with:

imagePickerDelegate = MealPhotoDelegate()

That's it. It will work now.

As a side note, there is no reason why your MealPhotoDelegate should extend UIViewController. Make it extend NSObject instead. And you the fix the new issues by using the proper code.

Here's how it should be:

class MealPhotoDelegate: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    var placeholder: UIImageView?

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

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }

        if let placeholder = placeholder {
            placeholder.image = selectedImage
        }

        picker.dismiss(animated: true, completion: nil)
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!