获取保存到照片库的图像的 PHAsset/localIdentifier
Posted
技术标签:
【中文标题】获取保存到照片库的图像的 PHAsset/localIdentifier【英文标题】:Get PHAsset/localIdentifier of image saved to photo library 【发布时间】:2021-01-02 23:12:30 【问题描述】:我正在使用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
的元数据中写一些东西,我不确定。
【问题讨论】:
重构你的技术以使用 PHAssetChangeRequest,网上有很多例子,placeholderForCreatedAsset 会有正确的 localIdentifier。 @PranavKasetti 看起来很有希望。谢谢! 【参考方案1】:试试这个保存图片的逻辑:
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")
【讨论】:
以上是关于获取保存到照片库的图像的 PHAsset/localIdentifier的主要内容,如果未能解决你的问题,请参考以下文章