mafioso mafioso - 4 months ago 59
iOS Question

How to add latest photo of photo library to uiimageview using Swift?

Is there a way to add the latest photo of my photo library to an uiimageview? I've tried nearly everything but nothing works.

Answer

Swift 3

let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [SortDescriptor(key: "creationDate", ascending: true)]

let fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)

let last = fetchResult.lastObject

if let lastAsset = last {
  let options = PHImageRequestOptions()
  options.version = .current

  PHImageManager.default().requestImage(
    for: lastAsset,
    targetSize: imageView.bounds.size,
    contentMode: .aspectFit,
    options: options,
    resultHandler: { image, _ in
      DispatchQueue.main.async {
        self.imageView.image = image
      }
    }
  )
}

Swift 2

@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    let fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]

    let fetchResult = PHAsset.fetchAssetsWithMediaType(.Image, options: fetchOptions)

    let last = fetchResult.lastObject

    if let lastAsset = last {
        let options = PHImageRequestOptions()
        options.version = .Current
        options.deliveryMode = .HighQualityFormat

        PHImageManager.defaultManager().requestImageForAsset(
            lastAsset as! PHAsset,
            targetSize: imageView.bounds.size,
            contentMode: .AspectFit,
            options: options,
            resultHandler: { image, _ in
                dispatch_async(dispatch_get_main_queue(), {
                    self.imageView.image = image
                })
            }
        )
    }
}
Comments