I wrote an extension that takes into account all possible cases:
- If access is allowed, then the code
onAccessHasBeenGranted
will be run.
- If access is not determined, then
requestAuthorization(_:)
will be called.
- If the user has denied your app photo library access, then the user will be shown a window offering to go to settings and allow access. In this window, the "Cancel" and "Settings" buttons will be available to him. When he presses the "settings" button, your application settings will open.
Usage example:
PHPhotoLibrary.execute(controller: self, onAccessHasBeenGranted: {
// access granted...
})
Extension code:
import Photos
import UIKit
public extension PHPhotoLibrary {
static func execute(controller: UIViewController,
onAccessHasBeenGranted: @escaping () -> Void,
onAccessHasBeenDenied: (() -> Void)? = nil) {
let onDeniedOrRestricted = onAccessHasBeenDenied ?? {
let alert = UIAlertController(
title: "We were unable to load your album groups. Sorry!",
message: "You can enable access in Privacy Settings",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Settings", style: .default, handler: { _ in
if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(settingsURL)
}
}))
controller.present(alert, animated: true)
}
let status = PHPhotoLibrary.authorizationStatus()
switch status {
case .notDetermined:
onNotDetermined(onDeniedOrRestricted, onAccessHasBeenGranted)
case .denied, .restricted:
onDeniedOrRestricted()
case .authorized:
onAccessHasBeenGranted()
@unknown default:
fatalError("PHPhotoLibrary::execute - \"Unknown case\"")
}
}
}
private func onNotDetermined(_ onDeniedOrRestricted: @escaping (()->Void), _ onAuthorized: @escaping (()->Void)) {
PHPhotoLibrary.requestAuthorization({ status in
switch status {
case .notDetermined:
onNotDetermined(onDeniedOrRestricted, onAuthorized)
case .denied, .restricted:
onDeniedOrRestricted()
case .authorized:
onAuthorized()
@unknown default:
fatalError("PHPhotoLibrary::execute - \"Unknown case\"")
}
})
}