From a5369701b02c90eeb5fc98ea5cf44d61fe9bbd24 Mon Sep 17 00:00:00 2001 From: ryanzhao Date: Tue, 24 Aug 2021 10:27:57 +1000 Subject: [PATCH] Fix the crash when seleting photos --- .../PhotoLibrary.swift | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/Session/Media Viewing & Editing/PhotoLibrary.swift b/Session/Media Viewing & Editing/PhotoLibrary.swift index b5e011da2..164c8b542 100644 --- a/Session/Media Viewing & Editing/PhotoLibrary.swift +++ b/Session/Media Viewing & Editing/PhotoLibrary.swift @@ -221,6 +221,10 @@ class PhotoCollectionContents { class PhotoCollection { private let collection: PHAssetCollection + + // The user never sees this collection, but we use it for a null object pattern + // when the user has denied photos access. + static let empty = PhotoCollection(collection: PHAssetCollection()) init(collection: PHAssetCollection) { self.collection = collection @@ -275,11 +279,30 @@ class PhotoLibrary: NSObject, PHPhotoLibraryChangeObserver { deinit { PHPhotoLibrary.shared().unregisterChangeObserver(self) } + + private lazy var fetchOptions: PHFetchOptions = { + let fetchOptions = PHFetchOptions() + fetchOptions.sortDescriptors = [NSSortDescriptor(key: "endDate", ascending: true)] + return fetchOptions + }() func defaultPhotoCollection() -> PhotoCollection { - guard let photoCollection = allPhotoCollections().first else { - owsFail("Could not locate Camera Roll.") + var fetchedCollection: PhotoCollection? + PHAssetCollection.fetchAssetCollections( + with: .smartAlbum, + subtype: .smartAlbumUserLibrary, + options: fetchOptions + ).enumerateObjects { collection, _, stop in + fetchedCollection = PhotoCollection(collection: collection) + stop.pointee = true } + + guard let photoCollection = fetchedCollection else { + Logger.info("Using empty photo collection.") + assert(PHPhotoLibrary.authorizationStatus() == .denied) + return PhotoCollection.empty + } + return photoCollection }