[英]Get PHAsset/localIdentifier of image saved to photo library
I'm using UIImageWriteToSavedPhotosAlbum
to save images to the Photos app.我正在使用
UIImageWriteToSavedPhotosAlbum
将图像保存到照片应用程序。 This was the only function I found that lets you do this.这是我发现的唯一可以让您执行此操作的 function。
Here's my code:这是我的代码:
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
}
}
The image is successfully saved to the Photos app.图像已成功保存到照片应用程序。 However, I need to retain a reference to it, preferably its
localIdentifier
, so I can find it among the user's other photos in the future.但是,我需要保留对它的引用,最好是它的
localIdentifier
,以便将来我可以在用户的其他照片中找到它。
For example, when I call fetchAllPhotos
later, I need some way to locate the cactus photo that I had saved.例如,当我稍后调用
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")
}
}
}
}
Is there any way I can do this?有什么办法可以做到这一点吗? The
UIImageWriteToSavedPhotosAlbum
completion handler references the UIImage
, so maybe I can create a PHAsset
from it? UIImageWriteToSavedPhotosAlbum
完成处理程序引用了UIImage
,所以也许我可以从中创建一个PHAsset
? Or maybe I can write something to the UIImage
's metadata, I'm not sure.或者也许我可以在
UIImage
的元数据中写一些东西,我不确定。
Try this for the saving image logic:试试这个保存图像逻辑:
try PHPhotoLibrary.shared().performChangesAndWait {
let imgReq = PHAssetChangeRequest.creationRequestForAsset(from: image)
self.localID = imgReq.placeholderForCreatedAsset.localIdentifier
}
You can get the local ID as follows:您可以通过以下方式获取本地 ID:
photos.enumerateObjects { (asset, index, stop) in
if asset.localIdentifier == self.localID {
print("photo was found")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.