0

Photos and videos are not saving in my custom photo album (TestAlbum). Instead, it is saving in the Camera Roll. Can you kindly help me to identify the issue and help me to correct the code.

PHPhotoLibrary.shared().performChanges({
    let albumName = "TestAlbum"
    let assetCollection: PHAssetCollection!
    let fetchOptions = PHFetchOptions()
    PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: albumName)

    fetchOptions.predicate = NSPredicate(format: "title = %@", albumName)

    let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)

    if let _: AnyObject = collection.firstObject {
        collection.firstObject
    }

    let options = PHAssetResourceCreationOptions()
    options.shouldMoveFile = true

    let creationRequest = PHAssetCreationRequest.forAsset()

    creationRequest.addResource(with: .video, fileURL: outputFileURL, options: options)
}, completionHandler: { success, error in
    if !success {
        print("Could not save movie to photo library: \(String(describing: error))")
    }
    cleanUp()
})
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Subs Dba
  • 9
  • 1
  • 2
  • Do a `performChanges()` to only run a `creationRequestForAssetCollection(withTitle:)`. In the completion handler, do another `performChanges()` to actually add your asset to the collection. EDIT: I don't know if it's actually important, but I use `creationRequest.addAsset()` instead of `creationRequest.addResource()`. It's been a long time since I wrote this code in Objective-C – Alejandro Iván Dec 20 '17 at 22:31
  • Thank you for your update but It did not fix the issue. – Subs Dba Dec 20 '17 at 22:58
  • @AlejandroIván Hi, Thanks for good suggestions But I want to set `.shouldMoveFile` to `true` then How do I do with `creationRequestForAssetCollection`? there is no way to put options parameters for `addAssets` – doori Oct 18 '21 at 07:49

1 Answers1

0

As in the comments above I would separate the creation of the photo album and the saving of your photo/video into two performChanges blocks. But I don't see anyway in your code where you are actually adding the asset (photo/video) to your asset collection (photo album). To do that do as follows

let assetPlaceholder = creationRequest.placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(for:collection)
if let changeRequest = albumChangeRequest, let placeholder = assetPlaceholder {
    changeRequest.addAssets(NSArray(array:[placeholder]))
}
adamfowlerphoto
  • 2,708
  • 1
  • 11
  • 24