iOS Swift/개발 이모저모

[사진]촬영 후 바로 아이폰 앨범에 저장하기

호두빵 2022. 12. 27. 17:25

  func saveImage(image : UIImage) {
    let data = image.jpegData(compressionQuality: 0.9)!
    PHPhotoLibrary.requestAuthorization { [unowned self] status in
        if status == .authorized {
            PHPhotoLibrary.shared().performChanges({
                let creationRequest = PHAssetCreationRequest.forAsset()
                creationRequest.addResource(with: .photo, data: data, options: nil)
            }, completionHandler: { success, error in
                if success {
                    print("hey it's success \(success)")
                }
                if let error = error {
                    print("Error occured while saving photo to photo library: \(error)")
                }
            })
        }
    }
}

 

오늘은 아이폰 카메라로 촬영한 사진을 기기의 앨범에 저장하는 방법을 알아봤습니다. 위 코드에서 중요한 것은 authorization status가 .authorized인지 먼저 확인해줘야 합니다. 만약 그렇다면 그 때 PHPhotoLibrary.shared().performChanges를 통해서 creationRequest.addResource를 해주고 여기에 data를 우리가 찍었던 이미지의 jpegData를 전달해주면 됩니다. completionHandler를 통해서 성공적으로 작업이 이뤄졌을 때와 에러가 발생했을 때를 나눠서 처리해주면 끄읕~ 생각보다 간단하게 앨범에 저장이 가능했습니다. 

 

func writeToPhotoAlbum(image: UIImage) {
	UIImageWriteToSavedPhotosAlbum(image, self, #selector(saveError), nil)
}
@objc func saveError(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        if let error = error {
            print("error: \(error.localizedDescription)")
        } else {
            print("Save completed!")
        }
    }

위 코드처럼 UIIMageWriteToSavedPhotosAlbum을 활용할수도 있다고 합니다. 다만 저는 첫번째 코드가 더 명확하고 직관적인 것 같다는 생각이 듭니다.

 

아래의 스택오버플로우 글을 참고하여 작성한 글입니다!

 

https://stackoverflow.com/questions/50394158/ios-save-to-photos-not-working

 

 

iOS save to Photos not working

I am developing my app using Swift 4 and iOS 11. The problem is I can have the UIImage shown in the UIImageView, but I cannot save it into my iPhone's Photo Album. I have been searching for a long...

stackoverflow.com