'Retrieving Video Asset After Saving it to Gallery

I am trying to save a video to Gallery and after that retrieving the asset, in ios 12 it worked fine, now testing it in ios 13 is not working anymore. The video is correctly saved, but the asset retrieved is not the correct one, instead, it is another from the library.

PHPhotoLibrary.shared().performChanges({
    PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: filePath)
}) { completed, error in
    if completed {
        let fetchOptions = PHFetchOptions()
        fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]

        let fetchResult = PHAsset.fetchAssets(with: .video, options: fetchOptions).lastObject
        GeneralUtils().shareVideoFacebook(fetchResult!, self)
    }

}


Solution 1:[1]

I just found the solution to this problem. You can ask for a local identifier of the saved image.

var id: String?
PHPhotoLibrary.shared().performChanges({
    let collection = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: filePath)
    id = collection?.placeholderForCreatedAsset?.localIdentifier
}) { completed, error in
    if completed {
        let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [id!], options: .none).firstObject
        GeneralUtils().shareVideoFacebook(fetchResult!, self)
    }                        
}

Solution 2:[2]

   DispatchQueue.global(qos: .background).async {
        if let url = URL(string: url),
           let urlData = NSData(contentsOf: url)
        { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            let filePath="\(documentsPath)/file.mp4"
            DispatchQueue.main.async {
                urlData.write(toFile: filePath, atomically: true)
                PHPhotoLibrary.shared().performChanges({
            self.instagramVideoId =  PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: filePath))?.placeholderForCreatedAsset?.localIdentifier
                }) { completed, _ in
                    if completed {
                        let url = URL(string: "instagram://library?LocalIdentifier=\(self.instagramVideoId!)")!
                        DispatchQueue.main.async {
                            if UIApplication.shared.canOpenURL(url) {
                                UIApplication.shared.open(url)
                            } else {
                            }
                        }
                    }
                }
            }
        }
        self.hideLoader()
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rmaddy
Solution 2 Dharman