将图像保存到照片库并检索URL

时间:2020-09-11 07:43:45

标签: swift swiftui

我可以使用以下代码将图像保存到我的照片库:

        PHPhotoLibrary.shared().performChanges({
            PHAssetCreationRequest
                .creationRequestForAssetFromImage(atFileURL: outfileURL)
        }) { (saved, err) in
            print("Saved?", saved)
            if (saved) {
                DispatchQueue.main.async {
                    onComplete(outfileURL.absoluteString)                        
                }
            }
        }

但是我正在尝试加载刚刚保存在Image(SwiftUI)中的图像,并且想要获取新的图像fileURL。 outfileURL是一个临时文件,不会保留。请注意,这是一个gif-如果有任何影响。

我正在尝试使用PHObjectPlaceholder,但我仍然不知道如何获取位置:

            var placeHolder: PHObjectPlaceholder? = nil
            PHPhotoLibrary.shared().performChanges({
                let changeRequest = PHAssetCreationRequest.creationRequestForAssetFromImage(atFileURL: outfileURL)
                placeHolder = changeRequest?.placeholderForCreatedAsset
            }) { (saved, err) in
                print("Saved? \(saved) to location \(placeHolder?)") //<--- AAAARGH!!!!
                if (saved) {
                    DispatchQueue.main.async {
                        
                        onComplete(/*????*/)
                        
                    }
                }
            }
   

1 个答案:

答案 0 :(得分:1)

PHObjectPlaceholder中,您可以使用localIdentifier

let fetchOptions = PHFetchOptions()
let fetchResult: PHFetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [placeholder.localIdentifier], options: fetchOptions)
if let asset = fetchResult.firstObject {
    // Here you can get UIImage from PHAsset
} 

这是可能的解决方案:

    var placeHolder: PHObjectPlaceholder? = nil
    PHPhotoLibrary.shared().performChanges({
        let changeRequest = PHAssetCreationRequest.creationRequestForAssetFromImage(atFileURL: outfileURL)
        placeHolder = changeRequest?.placeholderForCreatedAsset
    }) { (saved, err) in
        if let localIdentifier = placeHolder?.localIdentifier, saved {
            let fetchOptions = PHFetchOptions()
            let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [localIdentifier], options: fetchOptions)
            if let phAsset = fetchResult.firstObject {
                let targetSize = CGSize(width: CGFloat(phAsset.pixelWidth), height: CGFloat(phAsset.pixelHeight))
                let options = PHImageRequestOptions()
                PHCachingImageManager.default().requestImage(for: phAsset, targetSize: targetSize, contentMode: .aspectFill, options: options) { (uiImage, info) in
                    DispatchQueue.main.async {
                        onComplete(uiImage)
                    }
                }
            }
        }
    }