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

标签 ios swift phasset photokit

我正在使用 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")
    }
}

关于ios - 获取保存到照片库的图像的 PHAsset/localIdentifier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65545089/

相关文章:

ios - Swift 3 编译器错误 : 'bytes' is unavailable: use withUnsafeBytes instead

ios - 数据格式错误,因此无法读取。存档时

ios - cocoapod 中缺少文件

swift - 为什么 NSPredicateaccessibilityIdentifier 失败?

macos - 在 Swift 中创建像这样的普通框窗口吗?

ios - 高内存使用循环通过 PHAsset 并调用 requestImageForAsset

ios - 如何获取图片的路径?

ios - 如何使用 PhotoKit 访问慢动作视频的 NSData/NSURL

objective-c - 从 url 加载 .plist 文件

iOS NETunnelProviderManager 保存多个配置