title: Get PHAsset/localIdentifier of image saved to photo library
body: <p>I'm using <a href="https://www.hackingwithswift.com/example-code/media/uiimagewritetosavedphotosalbum-how-to-write-to-the-ios-photo-album" rel="nofollow noreferrer"><code>UIImageWriteToSavedPhotosAlbum</code></a> to save images to the Photos app. This was the only function I found that lets you do this.</p>
  <p>Here's my code:</p>
  <pre><code>import UIKit
  import Photos
  
  class ViewController: UIViewController {
  
      /// photo of a cactus
      let photoURL = URL(string: &quot;https://raw.githubusercontent.com/aheze/DeveloperAssets/master/cactus.png&quot;)! /// 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(&quot;Finished saving image&quot;)
          
          /// how to get localIdentifier of the image?
          let asset = PHAsset() /// obviously this does not work...
          let localIdentifier = asset.localIdentifier
      }
  }
  </code></pre>
  <p>The image is successfully saved to the Photos app. However, I need to retain a reference to it, <strong>preferably its <code>localIdentifier</code></strong>, so I can find it among the user's other photos in the future.</p>
  <p>For example, when I call <code>fetchAllPhotos</code> later, I need some way to locate the cactus photo that I had saved.</p>
  <pre><code>var allPhotos: PHFetchResult&lt;PHAsset&gt;?
  
  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 == &quot;cactus&quot; {
                  print(&quot;photo has been found&quot;)
              }
          }
      }
  }
  </code></pre>
  <p>Is there any way I can do this? The <code>UIImageWriteToSavedPhotosAlbum</code> completion handler references the <code>UIImage</code>, so maybe I can create a <code>PHAsset</code> from it? Or maybe I can write something to the <code>UIImage</code>'s metadata, I'm not sure.</p>