0

I want to set the picture name to "PG-1000" and check if it was created before, if so, replace it. So I need to access the filename properties of the PHAssetChangeRequest.

let myAlbumName = "CustomAlbum"
var albumPlaceholder: PHObjectPlaceholder?

PHPhotoLibrary.shared().performChanges({
    let request = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: myAlbumName)
    albumPlaceholder = request.placeholderForCreatedAssetCollection
}, completionHandler: { success, error in
    
    guard let placeholder = albumPlaceholder else {
        return
    }
    
    let fetchResult = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [placeholder.localIdentifier], options: nil)
    
    guard let album = fetchResult.firstObject else {
        return
    }
    
    // Create and save
    PHPhotoLibrary.shared().performChanges({
        let assetRequest = PHAssetChangeRequest.creationRequestForAsset(from: image!)
        
        let assetPlaceholder = assetRequest.placeholderForCreatedAsset
       
        guard let albumChangeRequest = PHAssetCollectionChangeRequest(for: album) else {
            return
            }
        albumChangeRequest.addAssets([assetPlaceholder] as NSArray)
    }, completionHandler: { success, error in
        if success {
            print("Image saved to album \(myAlbumName)")
        } else {
        
     print("Error saving image: \(error?.localizedDescription ?? "Unknown error")")
        }
    })
})

The code is running fine. It takes the image and saves it with a default name in a custom album, but not with a custom name.

HangarRash
  • 7,314
  • 5
  • 5
  • 32
richard
  • 3
  • 3
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community Mar 17 '23 at 19:25

1 Answers1

0

can this work the only downside i dont know hot to add the image name to asset when creating custom album with custom name any ideas? many thanks i been tring this for months with no luck

func saveImageToCustomAlbum(image: UIImage, albumName: String, imageName: String) {

    // Check if the album already exists
    let fetchOptions = PHFetchOptions()
    fetchOptions.predicate = NSPredicate(format: "title = %@", albumName)
    let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
    
    if let album = collection.firstObject {
        
        // Album exists, add image to album
        PHPhotoLibrary.shared().performChanges({
            let creationRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
            let addAssetRequest = PHAssetCollectionChangeRequest(for: album)
            let assetPlaceholder = creationRequest.placeholderForCreatedAsset
            addAssetRequest?.addAssets([assetPlaceholder!] as NSFastEnumeration)
        }) { (_, _) in
            print("Image saved to existing album.")
        }
        
    } else {
        
        // Album does not exist, create album and add image
        var albumPlaceholder: PHObjectPlaceholder?
        PHPhotoLibrary.shared().performChanges({
            let createAlbumRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: albumName)
            albumPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection
        }) { [weak self] success, error in
           
            guard let strongSelf = self else { return }
            if success {
                let fetchResult = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [albumPlaceholder!.localIdentifier], options: nil)
                if let album = fetchResult.firstObject {
                    PHPhotoLibrary.shared().performChanges({
                        let creationRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
                        let addAssetRequest = PHAssetCollectionChangeRequest(for: album)
                        let assetPlaceholder = creationRequest.placeholderForCreatedAsset
                        addAssetRequest?.addAssets([assetPlaceholder] as NSFastEnumeration)
                    }) { (_, _) in
                        print("Image saved to new album.")
                    }
                }
            } else {
                print("Error creating album: \(error?.localizedDescription ?? "Unknown error")")
            }
        }
        
    }
    
    // Get identifier of the saved image
    let options = PHFetchOptions()
    options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
    let result = PHAsset.fetchAssets(withLocalIdentifiers: [imageName], options: options)
    if let asset = result.firstObject {
        let identifier = asset.localIdentifier
        print("Image identifier: ########################################################################### \(identifier)")
    }
richard
  • 3
  • 3