From 1cdd17f07de43614db3a0dacd3607f9e5cb98dc6 Mon Sep 17 00:00:00 2001 From: "jstephen@redhat.com" Date: Tue, 4 Jan 2022 16:24:54 -0500 Subject: [PATCH] Handle Photo Library privacy settings correctly If photo library access is denied by the user then FreeOTP will no longer attempt to read from the photo gallery, falling back to the default FreeOTP token icon. Resolves: https://github.com/freeotp/freeotp-ios/issues/258 --- FreeOTP/ImageDownloader.swift | 36 +++++++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/FreeOTP/ImageDownloader.swift b/FreeOTP/ImageDownloader.swift index cb0fe8e..aada3e6 100644 --- a/FreeOTP/ImageDownloader.swift +++ b/FreeOTP/ImageDownloader.swift @@ -32,6 +32,19 @@ class ImageDownloader : NSObject { super.init() } + func isPHAssetAuthorized(_ status: PHAuthorizationStatus) -> Bool! { + switch status { + case .denied, .restricted: + return false + case .notDetermined: + return nil + case .authorized, .limited: + return true + @unknown default: + return false + } + } + func fromPHAsset(_ asset: PHAsset, completion: @escaping (UIImage) -> Void) { let opts: PHImageRequestOptions = PHImageRequestOptions() opts.isSynchronous = true @@ -49,13 +62,28 @@ class ImageDownloader : NSObject { } func fromALAsset(_ asset: URL, completion: @escaping (UIImage) -> Void) { - if asset.scheme == "assets-library" { - let rslt = PHAsset.fetchAssets(withALAssetURLs: [asset], options: nil) - if rslt.count > 0 { - return fromPHAsset(rslt[0] , completion: completion) + let status = PHPhotoLibrary.authorizationStatus() + let authorized = isPHAssetAuthorized(status) + var access_granted = false + + if (authorized == false) { + // shortcut completion + } else if (authorized == nil) { + PHPhotoLibrary.requestAuthorization { (status) -> Void in + if (self.isPHAssetAuthorized(status) == true) { + access_granted = true + } } } + if (authorized == true || access_granted == true) { + if asset.scheme == "assets-library" { + let rslt = PHAsset.fetchAssets(withALAssetURLs: [asset], options: nil) + if rslt.count > 0 { + return fromPHAsset(rslt[0] , completion: completion) + } + } + } return completion(DEFAULT) }