Search code examples
swifticloudphotokit

Add assets to an iCloud shared photo album programmatically


Are there any limitations on using PhotoKit to add photos to Shared iCloud photo albums? While I can add new photos to AssetCollections that are regular albums, it does not work at all if the AssetCollection represents an iCloud sharing album. Do I also need to add a different type of PHAsset?

If I change the fetchAssetCollections call to use .albumRegular instead of .albumCloudShared, the code below works. Otherwise I get an error:

The operation couldn't be completed. (PHPhotosErrorDomain error -1.)

let sharedAlbums = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumCloudShared, options: nil)

let target = sharedAlbums.firstObject

PHPhotoLibrary.shared().performChanges({
    let assetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: wantedimage)
    let assetPlaceHolder = assetChangeRequest.placeholderForCreatedAsset
    let albumChangeRequestShared = PHAssetCollectionChangeRequest(for: target!)
    let enumeration: NSArray = [assetPlaceHolder!]
    albumChangeRequestShared!.addAssets(enumeration)
}, completionHandler: { result, error in 
    print(result)
    print(error)
    print(error?.localizedDescription)
})



Solution

  • Yes, you can't add images to an iCloud shared album.

    Prior to performing a change request you should call canPerform(_:) on the PHAssetCollection.

    If you call canPerform(_:) on a PHAssetCollectionSubtype of albumCloudShared it will return false.

    For example:

        print(collection.canPerform(.createContent)) //false
         
        print(collection.canPerform(.addContent)) //false 
    

    I had this same problem and submitted a feature request via the Feedback app.