[swift] 앨범에 대한 Swift 퍼미션(Permission) 요청 방법.
앱에서 앨범에 대한 접근 권한을 요청하려면 NSPhotoLibraryUsageDescription 키를 Info.plist 파일에 추가해야 합니다. 이 키를 추가하면 사용자에게 앨범 접근에 대한 이유를 설명할 수 있는 메시지가 표시됩니다.
-
먼저, Info.plist 파일을 엽니다.
-
<dict>
태그 안에 다음과 같이 NSPhotoLibraryUsageDescription 키와 이에 해당하는 값인 설명 메시지를 추가합니다.<key>NSPhotoLibraryUsageDescription</key> <string>사진 앨범에 접근할 권한이 필요합니다.</string>
여기서 “사진 앨범에 접근할 권한이 필요합니다.”는 앱에서 앨범에 접근하려고 할 때 나타나는 메시지입니다.
-
앱에서 앨범에 접근하기 전에 사용자에게 권한을 요청해야 합니다.
import Photos PHPhotoLibrary.requestAuthorization { (status) in switch status { case .authorized: // 권한이 허용되었을 때 처리할 작업 break case .denied, .restricted, .notDetermined: // 권한이 거부되었거나 아직 결정되지 않았을 때 처리할 작업 break @unknown default: break } }
PHPhotoLibrary.requestAuthorization(completionHandler:)
메서드를 호출하여 앨범 접근 권한을 요청합니다. 사용자가 권한을 허용하거나 거부하면 completion handler가 호출됩니다. 권한 상태에 따라 필요한 작업을 수행하면 됩니다.권한 상태에 대한 설명은 다음과 같습니다:
.authorized
: 앨범 접근이 허용되었을 때.denied
: 앨범 접근이 거부되었을 때.restricted
: 앨범 접근이 제한되었을 때.notDetermined
: 앨범 접근 권한이 아직 결정되지 않았을 때
-
사용자가 권한을 거부한 경우 앱 설정으로 사용자를 안내하여 권한을 활성화할 수 있도록 할 수 있습니다.
let settingsUrl = URL(string: UIApplication.openSettingsURLString) if let url = settingsUrl { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } }
UIApplication.shared.open(_:options:completionHandler:)
메서드를 호출하여 앱 설정 화면으로 사용자를 이동시킵니다.
위의 단계를 따르면 앱에서 앨범에 대한 권한을 요청할 수 있습니다. 앨범 접근 권한을 허용 받은 후에는 해당 권한에 따라 앨범에 접근할 수 있습니다.
참고 자료
- Apple Developer Documentation - Requesting Authorization to Access Photos
- Apple Developer Documentation - NSPhotoLibraryUsageDescription