Swift3 – アルバムから写真を選択して取得する方法

環境

  • swift
  • swift3
  • xcode
  • xcode8
  • imagePickerController
  • UIImagePickerControllerOriginalImage
  • UIImagePickerControllerDelegate

カメラアルバムを表示させ

     /*

     カメラアルバムを表示させる関数

     */


    func Choiceimage() {


        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
            let picker = UIImagePickerController()
            picker.modalPresentationStyle = UIModalPresentationStyle.popover
            picker.delegate = self
            picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
            if let popover = picker.popoverPresentationController {
                popover.sourceView = self.view
                popover.permittedArrowDirections = UIPopoverArrowDirection.any
            }
            self.present(picker, animated: true, completion: nil)
        }
    }

関数を実行する

Choiceimage()

カメラが選択し終わった時に実行される関数

     /*

     カメラが選択し終わった時に実行される関数

     */


    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {


        //変数pickedImageに画像が入っている


        }
        //カメラアルバムの画面を閉じる
        picker.dismiss(animated: true, completion: nil)
    }

UIImage の画像をカメラロールに画像を保存

       //UIImage の画像をカメラロールに画像を保存
        UIImageWriteToSavedPhotosAlbum(該当するUIImage, self, #selector(self.showResultOfSaveImage(_:didFinishSavingWithError:contextInfo:)), nil)

     /*

     保存を試みた結果をダイアログで表示

     */
    @objc func showResultOfSaveImage(_ image: UIImage, didFinishSavingWithError error: NSError!, contextInfo: UnsafeMutableRawPointer) {
        var title = "保存完了"
        var message = "カメラロールに保存しました"
        if error != nil {
            title = "エラー"
            message = "保存に失敗しました"

        }
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        // OKボタンを追加
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        // UIAlertController を表示
        self.present(alert, animated: true, completion: nil)
    }
藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

未整理記事