5// Created by Alex Chan on 08/06/2023.
12 /// Returns a list of all the albums that contain this asset.
13 func albums() -> [PHAssetCollection] {
14 var result: [PHAssetCollection] = []
17 .fetchAssetCollectionsContaining(self, with: .album, options: nil)
18 .enumerateObjects({ (collection, index, stop) in
19 result.append(collection)
25 func originalFilename() -> String {
26 PHAssetResource.assetResources(for: self).first!.originalFilename
29 /// Returns true if an asset is in the given album, false otherwise.
30 private func isInAlbum(_ album: PHAssetCollection) -> Bool {
31 return albums().contains(where: { collection in
36 /// Remove a photo from an album.
38 /// This expects to be run inside a performChangesAndWait change block;
39 /// see https://developer.apple.com/documentation/photokit/phphotolibrary/1620747-performchangesandwait.
40 func remove(fromAlbum album: PHAssetCollection) -> Void {
42 PHAssetCollectionChangeRequest(for: album)!
44 changeAlbum.removeAssets([self] as NSFastEnumeration)
47 /// Add a photo to an album.
49 /// This expects to be run inside a performChangesAndWait change block;
50 /// see https://developer.apple.com/documentation/photokit/phphotolibrary/1620747-performchangesandwait.
51 func add(toAlbum album: PHAssetCollection) -> Void {
53 PHAssetCollectionChangeRequest(for: album)!
55 changeAlbum.addAssets([self] as NSFastEnumeration)
58 /// Toggle a photo's inclusion in an album.
60 /// If the photo is already in the album, remove it. If the photo isn't
61 /// in the album, add it.
63 /// This expects to be run inside a performChangesAndWait change block;
64 /// see https://developer.apple.com/documentation/photokit/phphotolibrary/1620747-performchangesandwait.
65 func toggle(inAlbum album: PHAssetCollection) -> Void {
67 PHAssetCollectionChangeRequest(for: album)!
69 let assets = [self] as NSFastEnumeration
71 if self.isInAlbum(album) {
72 changeAlbum.removeAssets(assets)
74 changeAlbum.addAssets(assets)