Swift (스위프트): 사진 라이브러리, 카메라 사용 (스토리보드)
info.plist에서 권한 허용을 묻는 메시지를 설정합니다. 
사진을 표시하고자 하는 뷰 컨트롤러 안에 이미지 피커 컨트톨러를 생성합니다.
1
2
// 사진: 이미지 피커 컨트롤러 생성
let imagePickerController = UIImagePickerController()
viewDidLoad에 컨트롤러와 delegate를 연결합니다. 또한 앱을 최초로 실행했을 때 권한 허용 여부를 묻는 메시지를 출력하는 코드를 작성합니다. (import Photos 필요)
1
2
3
4
5
6
7
8
9
10
11
12
13
override func viewDidLoad() {
super.viewDidLoad()
// 사진: 이미지 피커에 딜리게이트 생성
imagePickerController.delegate = self
// 사진, 카메라 권한 (최초 요청)
PHPhotoLibrary.requestAuthorization { status in
}
AVCaptureDevice.requestAccess(for: .video) { granted in
}
}
카메라 또는 라이브러리를 실행할 버튼을 생성하고 컨트롤러에 IB액션 함수를 연결합니다. 미리보기 이미지 뷰를 만들고 IB아웃렛 연결합니다.
카메라 버튼 액션 함수의 내용을 작성합니다. 권한별 설정을 하려면 switch문을 사용하여 AVCaptureDevice.authorizationStatus(for: AVMediaType.video)의 분기별로 작성합니다. (import AVFoundation 필요)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// 사진: 카메라 켜기 - 시뮬레이터에서는 카메라 사용이 불가능하므로 에러가 발생.
@IBAction func btnTakePhoto(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
self.imagePickerController.sourceType = .camera
switch PHPhotoLibrary.authorizationStatus() {
case .notDetermined:
simpleAlert(self, message: "notDetermined")
UIApplication.shared.open(URL(string: "UIApplication.openSettingsURLString")!)
case .restricted:
simpleAlert(self, message: "restricted")
case .denied:
simpleAlert(self, message: "denied")
case .authorized:
self.present(self.imagePickerController, animated: true, completion: nil)
@unknown default:
simpleAlert(self, message: "unknown")
}
} else {
print("카메라 사용이 불가능합니다.")
simpleAlert(self, message: "카메라 사용이 불가능합니다.")
}
/**
switch PHPhotoLibrary.authorizationStatus() {
.notDetermined - User has not yet made a choice with regards to this application
.restricted - This application is not authorized to access photo data. The user cannot change this application’s status, possibly due to active restrictions
.denied - User has explicitly denied this application access to photos data.
.authorized - User has authorized this application to access photos data.
}
*/
}
참고로 Xcode의 시뮬레이터는 카메라 사용이 불가능하므로 카메라 사용이 불가능한 경우 예외 처리를 합니다.
포토 라이브러리 버튼의 코드 및 권한 설정도 진행합니다. 사진 라이브러리의 경우 PHPhotoLibrary.authorizationStatus() 를 사용합니다. (import Photos 필요)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 사진: 라이브러리 켜기
@IBAction func btnLoadPhoto(_ sender: Any) {
self.imagePickerController.sourceType = .photoLibrary
switch PHPhotoLibrary.authorizationStatus() {
case .notDetermined:
simpleAlert(self, message: "notDetermined")
UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
case .restricted:
simpleAlert(self, message: "restricted")
case .denied:
simpleAlert(self, message: "denied")
case .authorized:
self.present(self.imagePickerController, animated: true, completion: nil)
case .limited:
simpleAlert(self, message: "limited")
@unknown default:
simpleAlert(self, message: "unknown")
}
}
이미지 피커 뷰의 딜리게이트에 대한 함수를 작성합니다. 이 부분은 사진을 찍었거나 포토 라이브러리에서 사진을 고른 후에 실행할 작업을 작성합니다.
1
2
3
4
5
6
7
8
9
10
11
// 사진: 딜리게이트 구현한 뷰 컨트롤러 생성
extension DiffuserAddViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
imgPhoto.image = image
}
dismiss(animated: true, completion: nil)
}
}
버튼을 누른 경우
이미지를 선택한 경우
This post is licensed under
CC BY 4.0
by the author.


