I'm trying to add a video asset to my app's photo library, via drag/drop from the Photos app. I managed to get the video's URL from the drag, but when I try to create the PHAsset for it I get an error:
PHExternalAssetResource: Unable to issue sandbox extension for /private/var/mobile/Containers/Data/Application/28E04EDD-56C1-405E-8EE0-7842F9082875/tmp/.com.apple.Foundation.NSItemProvider.fXiVzf/IMG_6974.mov
Here's my code to add the asset:
let url = URL(string: videoPath)!
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url)
}) { saved, error in
// Error !!
}
Addictionally, this check is true
in the debugger:
UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(videoPath) == true
Note that adding still images, much in the same way, works fine. And I naturally have photo library permissions enabled.
Any idea what I'm missing? I'm seeing the same error on iOS17.2 and iPadOS 17.2, with Xcode 15.2. Thanks for any tips ☺️
Ok got it working now ! 🎉
I was missing copying the contents to my own file, so we're still able to access it once the original is gone.
public func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: any UICollectionViewDropCoordinator) {
for item in coordinator.items {
// Check if the dropped item is a URL (for videos)
if item.dragItem.itemProvider.hasItemConformingToTypeIdentifier(AVFileType.mov.rawValue) {
item.dragItem.itemProvider.loadFileRepresentation(forTypeIdentifier: AVFileType.mov.rawValue) { (videoURL, error) in
if let droppedVideoURL = videoURL as? URL {
let fileManager = FileManager.default
let destination = fileManager.temporaryDirectory.appendingPathComponent("video123.mov")
try? fileManager.copyItem(at: droppedVideoURL, to: destination)
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: destination)
}) { saved, error in
if saved {
print("SAVED!")
}
}
}
}
}
}