UIImagePickerControllerを使ったカメラロールの操作を試してみました。
ImagePickerの表示
まずはカメラロールの操作の為に、Info.plistにNSPhotoLibraryUsageDescriptionというキーを追加します。
ここにはカメラロールの利用目的を書きます。
ここに書かれた文言が、アクセス許可ポップアップに表示されます。
ImagePicker(画像選択画面)の表示は下の通りです。
import UIKit
class ViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let c = UIImagePickerController()
present(c, animated: true)
}
}
アプリを立ち上げると、下のように画像選択画面が表示されます。
ImagePickerは、画像選択時・キャンセルボタン押下時のイベントを取る事ができます。
イベント取得は下のようにUIImagePickerControllerDelegate
を使います。
class ViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let c = UIImagePickerController()
c.delegate = self
present(c, animated: true)
}
}
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
}
}
ユーザーがカメラロールへのアクセスを許可しているかどうかは下メソッドで取得できます。
PHPhotoLibrary.requestAuthorization { status in
switch status {
case .authorized: print("authorized")
case .denied: print("denied")
case .notDetermined: print("NotDetermined")
case .restricted: print("Restricted")
}
}
不許可の場合にImagePickerを立ち上げると、下のような表示になります。
画像を取得する
選択画像の取得は、UIImagePickerControllerDelegateのimagePickerController:didFinishPickingMediaWithInfoメソッドで行います。
引数のinfoにUIImageが入っているので、下のように取り出します。
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as? UIImage
}
}
画像の他にも、メディアのタイプとメディアのURLを取得できます。
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info[UIImagePickerControllerMediaType] as? String
let imageUrl = info[UIImagePickerControllerReferenceURL] as? URL
}
}
UIImagePickerControllerのオプション
デフォルトでは、UIImagePickerControllerは画像しか取得できません。
下のようにmediaTypesを変更することで動画も扱えるようになります。
class ViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let c = UIImagePickerController()
c.mediaTypes = ["public.image", "public.movie"]
present(c, animated: true)
}
}
取扱可能なメディアはavailableMediaTypesメソッドで確認できます。
print(UIImagePickerController.availableMediaTypes(for: .photoLibrary))
UIImagePickerControllerのsourceTypeを.cameraにすればカメラ撮影での画像取得もできます。
class ViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let c = UIImagePickerController()
c.sourceType = .camera
present(c, animated: true)
}
}