Skip to main content

Blink/Photos/AssetHelpers.swift

1//
2// Helpers.swift
3// BlinkReviewer
4//
5// Created by Alex Chan on 08/06/2023.
6//
8import Foundation
9import Photos
11extension PHAsset {
12 /// Returns a list of all the albums that contain this asset.
13 func albums() -> [PHAssetCollection] {
14 var result: [PHAssetCollection] = []
16 PHAssetCollection
17 .fetchAssetCollectionsContaining(self, with: .album, options: nil)
18 .enumerateObjects({ (collection, index, stop) in
19 result.append(collection)
20 })
22 return result
23 }
25 func originalFilename() -> String {
26 PHAssetResource.assetResources(for: self).first!.originalFilename
27 }
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
32 collection == album
33 })
34 }
36 /// Remove a photo from an album.
37 ///
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 {
41 let changeAlbum =
42 PHAssetCollectionChangeRequest(for: album)!
44 changeAlbum.removeAssets([self] as NSFastEnumeration)
45 }
47 /// Add a photo to an album.
48 ///
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 {
52 let changeAlbum =
53 PHAssetCollectionChangeRequest(for: album)!
55 changeAlbum.addAssets([self] as NSFastEnumeration)
56 }
58 /// Toggle a photo's inclusion in an album.
59 ///
60 /// If the photo is already in the album, remove it. If the photo isn't
61 /// in the album, add it.
62 ///
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 {
66 let changeAlbum =
67 PHAssetCollectionChangeRequest(for: album)!
69 let assets = [self] as NSFastEnumeration
71 if self.isInAlbum(album) {
72 changeAlbum.removeAssets(assets)
73 } else {
74 changeAlbum.addAssets(assets)
75 }
76 }