微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

获取保存到照片库的图像的 PHAsset/localIdentifier

如何解决获取保存到照片库的图像的 PHAsset/localIdentifier

我正在使用 UIImageWriteToSavedPhotosAlbum 将图像保存到“照片”应用。这是我发现的唯一可以让您执行此操作的功能

这是我的代码

import UIKit
import Photos

class ViewController: UIViewController {

    /// photo of a cactus
    let photoURL = URL(string: "https://raw.githubusercontent.com/aheze/DeveloperAssets/master/cactus.png")! /// in my app it's actually a local URL,but this also works
    
    func savetoPhotos() {
        dispatchQueue.global().async {
            let data = try? Data(contentsOf: self.photoURL)
            let image = UIImage(data: data!)
            UIImageWritetoSavedPhotosAlbum(image!,self,#selector(self.image(_:didFinishSavingWithError:contextInfo:)),nil)
        }
    }

    /// called when the image saving is complete
    @objc func image(_ image: UIImage,didFinishSavingWithError error: NSError?,contextInfo: UnsafeRawPointer) {
        print("Finished saving image")
        
        /// how to get localIdentifier of the image?
        let asset = PHAsset() /// obvIoUsly this does not work...
        let localIdentifier = asset.localIdentifier
    }
}

图像已成功保存到“照片”应用。但是,我需要保留对它的引用,最好是它的 localIdentifier,以便我将来可以在用户的​​其他照片中找到它。

例如,当我稍后调用 fetchAllPhotos 时,我需要某种方法来定位我保存的仙人掌照片。

var allPhotos: PHFetchResult<PHAsset>?

func fetchAllPhotos() {
    let fetchOptions = PHFetchOptions() /// get all of user's photos
    allPhotos = PHAsset.fetchAssets(with: .image,options: fetchOptions)
    
    if let photos = allPhotos {
        photos.enumerateObjects { (asset,index,stop) in


            /// I need to find the image!  
            /// So I need to kNow its localIdentifier back when I saved it.
            if asset.localIdentifier == "cactus" {
                print("photo has been found")
            }
        }
    }
}

有什么办法可以做到这一点? UIImageWritetoSavedPhotosAlbum 完成处理程序引用 UIImage,所以也许我可以从中创建一个 PHAsset?或者也许我可以向 UIImage 的元数据写入一些内容,我不确定。

解决方法

试试这个保存图像的逻辑:

try PHPhotoLibrary.shared().performChangesAndWait {
    let imgReq = PHAssetChangeRequest.creationRequestForAsset(from: image)
    self.localID = imgReq.placeholderForCreatedAsset.localIdentifier
 }

您可以通过以下方式获取本地 ID:

photos.enumerateObjects { (asset,index,stop) in
    if asset.localIdentifier == self.localID {
        print("photo was found")
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。