Daniel Patriarca
Daniel Patriarca

Reputation: 365

Is there a way to control the sort order when you create a new album to save images onto photo library?

Summary: Is there a way to control the sort order for an album created by an app on a users device? I would like an album I created to sort by date, but it sorts by download order.

Details: I am using the function save() below to save a UIImage to an album on a user's iPhone. It works great but the image loses its original create time when the copy is saved. To address this I read the create time when I upload an image to the server. That way I just assign it to the image when the asset is created with assetChangeRequest.creationDate = storedImageDate

    PHPhotoLibrary.shared().performChanges({
        let assetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
        let assetPlaceholder = assetChangeRequest.placeholderForCreatedAsset
        let albumChangeRequest = PHAssetCollectionChangeRequest(for: assetCollection)
        assetChangeRequest.creationDate = storedImageDate
        let assetEnumeration:NSArray = [assetPlaceholder!]
        albumChangeRequest!.addAssets(assetEnumeration)

    }, completionHandler: { success, error in
        if error != nil {
            print("\(error?.localizedDescription ?? "")")
        }
    })

The above works great and when I look at the newly created image it is in the created album, the images have the correct date on the image, and the images viewed in camera roll are sorted by the image create date as expected. The issue arises when go to the album my app created for images. There the images have the image date, but they are sorted by the order they downloaded not the image. I also noticed that when I long press images in the album it lets me move the order around.

Did I do something wrong creating my album? Can I set it to sort by image date? Perhaps there is a way to change the sort order for my album? Is there a way to fetch loop through the album to order it by date?

This is the full function where an image is saved into a created album which does not sort by the image creation date.

func save(image:UIImage, albumName:String) {
    var albumFound = false
    var assetCollection: PHAssetCollection!
    var assetCollectionPlaceholder: PHObjectPlaceholder!

    // https://stackoverflow.com/questions/27008641/save-images-with-phimagemanager-to-custom-album
    // Check if the Album exists and get collection
    let fetchOptions = PHFetchOptions()
    fetchOptions.predicate = NSPredicate(format: "title = %@", albumName)
    let collection : PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)

    if let _: AnyObject = collection.firstObject {
        albumFound = true
        assetCollection = collection.firstObject
    } else {
        //If not found - Then create a new album
        PHPhotoLibrary.shared().performChanges({
            let createAlbumRequest : PHAssetCollectionChangeRequest = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: albumName)
            assetCollectionPlaceholder = createAlbumRequest.placeholderForCreatedAssetCollection
        }, completionHandler: { success, error in
            albumFound = success
            if (success) {
                let collectionFetchResult = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [assetCollectionPlaceholder.localIdentifier], options: nil)
                print(collectionFetchResult)
                assetCollection = collectionFetchResult.firstObject
            }
        })
    }
    if albumFound {
        PHPhotoLibrary.shared().performChanges({
            let assetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
            let assetPlaceholder = assetChangeRequest.placeholderForCreatedAsset
            let albumChangeRequest = PHAssetCollectionChangeRequest(for: assetCollection)
            assetChangeRequest.creationDate = storedImageDate
            let assetEnumeration:NSArray = [assetPlaceholder!]
            albumChangeRequest!.addAssets(assetEnumeration)

        }, completionHandler: { success, error in
            if error != nil {
                print("\(error?.localizedDescription ?? "")")
            }
        })
    }
}

Upvotes: 0

Views: 1264

Answers (1)

skg
skg

Reputation: 141

Instead of using addAssets like you did in performChanges 'albumChangeRequest!.addAssets(assetEnumeration)'.

You should use insertAssets at indexes which controls the position the images are added to the album, much like NSArray insertObject atIndex method.

Swift

func insertAssets(_ assets: NSFastEnumeration, 
             at indexes: IndexSet)

Objective-C

- (void)insertAssets:(id<NSFastEnumeration>)assets 
       atIndexes:(NSIndexSet *)indexes;

https://developer.apple.com/documentation/photokit/phassetcollectionchangerequest/1619447-insertassets

Upvotes: 0

Related Questions