I have created an album programmatically. I want to check if image already exists in album before adding new image. you can check with below code CustomAlbum.shared.saveImage(image: UIImage()) save image like this.
import Foundation
import Photos
class CustomAlbum {
static let albumName = "xyz"
static let shared = CustomAlbum()
var assetCollection: PHAssetCollection!
init() {
func fetchAssetCollectionForAlbum() -> PHAssetCollection! {
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", CustomAlbum.albumName)
let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
if let _: AnyObject = collection.firstObject {
return collection.firstObject!
}
return nil
}
if let assetCollection = fetchAssetCollectionForAlbum() {
self.assetCollection = assetCollection
return
}
PHPhotoLibrary.shared().performChanges({
PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: CustomAlbum.albumName)
}) { _, _ in
self.assetCollection = fetchAssetCollectionForAlbum()
}
}
func saveImage(image: UIImage) {
if assetCollection == nil { return }
PHPhotoLibrary.shared().performChanges({
let assetPlaceholder = PHAssetChangeRequest.creationRequestForAsset(from: image).placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection)
let assetEnumeration: NSArray = [assetPlaceholder!]
albumChangeRequest?.addAssets(assetEnumeration)
}, completionHandler: nil)
}
func allPhotos(albumName: String = "xyz", albumImages: @escaping ([UIImage]) -> Void) {
let group = DispatchGroup()
var images: [Image] = []
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", albumName)
let resultCollections = PHAssetCollection.fetchAssetCollections(
with: .album,
subtype: .albumRegular,
options: fetchOptions)
resultCollections.enumerateObjects({
(object, index, stop) -> Void in
let collection = object
let result = PHAsset.fetchAssets(in: collection, options: nil)
result.enumerateObjects({
(object, index, stop) -> Void in
group.enter()
images.append(object.getfullImage())
group.leave()
})
})
group.notify(queue: DispatchQueue.main) {
albumImages(images)
}
}
}
with this code i'm fetching all images of album and comparing against the image I want to save.
PHPhotoLibrary.shared().allPhotos { (images) in
let image = UIImage()
}