Utkarsh Sehgal
Utkarsh Sehgal

Reputation: 11

Duplicate file name when trying to save same image twice to Photo Library

I am trying to save an image to the user's photo library using PHPhotoLibrary and set the image file name at the time of saving the code below. This is working the first time, but if I then try to save the same image again with a different file name, it saves with the same file name as before.

Is there something I need to add to let the system know to save a new version of the image with a new file name?

PHPhotoLibrary.shared().performChanges ({
    let assetType:PHAssetResourceType = .photo
    let request:PHAssetCreationRequest = .forAsset()
    let createOptions:PHAssetResourceCreationOptions = PHAssetResourceCreationOptions()
    createOptions.originalFilename = "\(fileName)"
    request.addResource(with: assetType, data: image.jpegData(compressionQuality: 1)!, options: createOptions)
}, completionHandler: { success, error in
    if success == true && error == nil {
        print("Success saving image")
    } else {
        print("Error saving image: \(error!.localizedDescription)")
    }
})

Save the new image with the required file name

Upvotes: 1

Views: 186

Answers (2)

I could not find anything in Apple's Developer Documentation, but my guess is that PHPhotoLibrary has something that checks if the file is unique. Maybe be related to duplicate detection.

As a workaround, you have a couple of options. One is to make slight edits to the image. For instance, you could alter a few pixels so that the resulting image differs from the original.

Another approach, which I prefer because it avoids any visual changes to the image, is to modify the photo's metadata. For example, you could change the creation date by adding a second.

Upvotes: 0

Pawczak
Pawczak

Reputation: 1

Your code is fine, as long as it saves the photo (didn't test your code).

I came across the same issue as you described and after some testing i noticed that the same photo data is only renamed once. I also noticed that if you change anything in the photo data then renaming and saving file works just fine.

I managed to rename file succesfully by setting some random value in EXIF data, just choose any EXIF data key that is most useless to you.

I think iOS has some kind of duplicate recognition handling, because any change in data and renaming works just fine.

I also don't think that it's good way of doing this thing. But couldn't find anything that worked.

Upvotes: 0

Related Questions