본문 바로가기
iOS Swift/개발 이모저모

[사진]UIImagePickerController로 아이폰 기기 앨범의 이미지 선택하기

by 호두빵 2022. 12. 21.

    let imagePickerController = UIImagePickerController()
    
    
    func changeProfileImage() {
        let ac = UIAlertController(title: "PROFILE_CHANGE_TITLE".localized(), message: "PROFILE_CHANGE_INST".localized(), preferredStyle: .actionSheet)
        ac.addAction(UIAlertAction(title:"PROFILE_CHANGE_PHOTO".localized(), style: .default, handler: { action in
            print("camera clicked")
        }))
        ac.addAction(UIAlertAction(title:"PROFILE_CHANGE_ALBUM".localized(), style:.default,handler: { action in
            self.imagePickerController.delegate = self
            self.imagePickerController.sourceType = .photoLibrary
            self.imagePickerController.allowsEditing = true
            self.present(self.imagePickerController, animated: false, completion: nil)
        }))
        ac.addAction(UIAlertAction(title:"CANCEL".localized(), style: .cancel))
        present(ac, animated: true)
    }

UIImagePickerController를 선언해주고 두고두고 사용하기로 합니다. 기기 하단에서 올라오는 액션시트 형태를 활용했는데, UIAlertController를 만들어서 여기에 두가지 액션을 추가해줍니다. 첫번째는 사용자가 즉시 사진을 찍어서 프로필 사진을 바꾸는 것이고, 두번째는 앨범에 있는 사진 중에 골라서 만드는 것인데, 이번에는 두번째 것 먼저 실습을 해봅니다. delegate는 self로 지정해주고, sourceType은 당연히 .photoLibrary, 편집이 가능하도록 allowsEditing도 true로 설정해준 다음 imagePickerController를 보여주면 됩니다!

extension MyPageViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey.originalImage ]{
            if let image = info[.originalImage] as? UIImage {
                dismiss(animated: true) {
                    self.openCropVC(image: image)
                }
            }
            dismiss(animated: true, completion: nil)
        }
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        self.dismiss(animated: true, completion: nil)
    }
}

 

사용자가 사진 선택을 마치고나면 didFInishPickingMediaWithInfo,,,didFinish,,,뭔가 끝났을 때 써먹는 것 같죠? 선택된 이미지를 가지고 저는 원형으로 크롭하기를 원해서, cropViewController에 이미지값을 전달하여주고 UIImagePickerController는 dismiss하였습니다. 마찬가지로 아무 사진도 고르지 않고 취소하였을때도 해당 뷰컨트롤러가 사라져야하기 때문에 dismiss처리를 해줘야 합니다!