すごい初歩的なことですが、個人的に詰まったので備忘録として。
1.一番下のソースをコピペ
2.Info.plist に Privacy - Photo Library Usage Descriptionを追加する
の手順で動きます。
指摘とかあったらコメントしていただけるとありがたいです。
ViewController.swift
import UIKit
import Photos
class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
var imageView: UIImageView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// 画面に画像を表示するViewを作成
imageView = UIImageView()
imageView = UIImageView(frame: CGRect(x: 30, y: 40, width: 170, height: 220))
imageView!.layer.borderWidth = 1
// タップ時のアクションを設定する
let tapGestureRecognizer = UITapGestureRecognizer(target: self,action: #selector(imageTapped))
imageView!.isUserInteractionEnabled = true
imageView!.addGestureRecognizer(tapGestureRecognizer)
self.view.addSubview(imageView!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc
fileprivate func imageTapped(){
// アルバム(Photo liblary)の閲覧権限の確認
checkPermission()
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
print("present Start")
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
}
// アルバム(Photo liblary)の閲覧権限の確認をするメソッド
func checkPermission(){
let photoAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
switch photoAuthorizationStatus {
case .authorized:
print("auth")
case .notDetermined:
PHPhotoLibrary.requestAuthorization({
(newStatus) in
print("status is \(newStatus)")
if newStatus == PHAuthorizationStatus.authorized {
/* do stuff here */
print("success")
}
})
print("not Determined")
case .restricted:
print("restricted")
case .denied:
print("denied")
}
}
}