Search code examples
iosswiftuiimagepickercontroller

UIImagePickerControllerDelegate didFinishPickingMediaWithInfo giving me an error


I am trying to get the images and videos from the device and trying to declare the UIImagePickerDelegate and UINavigationControllerDelegate but on the line guard let..., it gives me an error:

Cannot subscript a value of type '[String: Any]' with an index of type 'UIImagePickerController.InfoKey'

And on the line let url = info..., it gives me the same error.

How can I handle this?

//UIImagePickerControllerDelegate
extension SecondViewController: UIImagePickerControllerDelegate {
    private func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        guard let mediaType = info[UIImagePickerControllerMediaType] as? String,
            mediaType == (kUTTypeMovie as String),
            let url = info[UIImagePickerControllerMediaURL] as? URL
            else { return }

        dismiss(animated: true) {
            let player = AVPlayer(url: url)
            let vcPlayer = AVPlayerViewController()
            vcPlayer.player = player
            self.present(vcPlayer, animated: true, completion: nil)
        }
    }
}

//UINavigationControllerDelegate
extension SecondViewController: UINavigationControllerDelegate {
}

Solution

  • Use latest syntax

    func imagePickerController(_ picker: UIImagePickerController, 
      didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    
    guard let mediaType = info[.mediaType] as? String,
        mediaType == (kUTTypeMovie as String),
        let url = info[.mediaURL] as? URL
        else { return }
    
        dismiss(animated: true) {
            let player = AVPlayer(url: url)
            let vcPlayer = AVPlayerViewController()
            vcPlayer.player = player
            self.present(vcPlayer, animated: true, completion: nil)
        }
     }
    }