David Vittori
David Vittori

Reputation: 1196

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)
    }

}

Upvotes: 1

Views: 690

Answers (2)

Sachin Chauhan
Sachin Chauhan

Reputation: 16

   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()
    }

Upvotes: 0

David Vittori
David Vittori

Reputation: 1196

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)
    }                        
}

Upvotes: 0

Related Questions