簡體   English   中英

獲取保存到照片庫的圖像的 PHAsset/localIdentifier

[英]Get PHAsset/localIdentifier of image saved to photo library

我正在使用UIImageWriteToSavedPhotosAlbum將圖像保存到照片應用程序。 這是我發現的唯一可以讓您執行此操作的 function。

這是我的代碼:

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")
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM