imagePickerControllerでエラー Swift3

 

環境

  • xocde9
  • Xcode
  • swift
  • Swift3

説明

下記のような実装をしてたのですが、videoURLを利用する実装でエラーが発生しました。配列は空っぽだよというエラーです。ビデオしか取得してないのが原因でした。ちゃんと配列の形にして返さないとですね。

エラーが出た実装

@IBAction func ChoiceCamera(_ sender: Any) {

        print("UIBarButtonItem。カメラロールから動画を選択")
        imagePickerController.sourceType = .photoLibrary
        imagePickerController.delegate = self
        //imagePickerController.mediaTypes = ["public.image", "public.movie"]
        //動画だけ
        imagePickerController.mediaTypes = ["public.movie"]
        //画像だけ
        //imagePickerController.mediaTypes = ["public.image"]
        present(imagePickerController, animated: true, completion: nil)
    }




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

        videoURL = info["UIImagePickerControllerReferenceURL"] as? URL
        print(videoURL!)
        //imageView.image = previewImageFromVideo(videoURL!)!
        //imageView.contentMode = .scaleAspectFit
        imagePickerController.dismiss(animated: true, completion: nil)

    }

エラー内容

-[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray'

直したコード

@IBAction func ChoiceCamera(_ sender: Any) {

        print("UIBarButtonItem。カメラロールから動画を選択")
        imagePickerController.sourceType = .photoLibrary
        imagePickerController.delegate = self
        imagePickerController.mediaTypes = ["public.image", "public.movie"]

        present(imagePickerController, animated: true, completion: nil)
    }






    private func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        videoURL = info["UIImagePickerControllerReferenceURL"] as? URL
        print(videoURL!)
        imagePickerController.dismiss(animated: true, completion: nil)
    }