Skip to content

Instantly share code, notes, and snippets.

@vaghul
Created September 5, 2016 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vaghul/1ce8f9150b9c48ee1a9f4f25ab0e553b to your computer and use it in GitHub Desktop.
Save vaghul/1ce8f9150b9c48ee1a9f4f25ab0e553b to your computer and use it in GitHub Desktop.
Snippet to get the last taken photo in iOS
import UIKit
import Photos
// I like to typealias my blocks, makes for easier reading
typealias ImageCallback = (UIImage? -> Void)
func fetchLastPhoto(resizeTo size: CGSize?, imageCallback: ImageCallback) {
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
// fetchOptions.fetchLimit = 1 // Available in iOS 9
if let fetchResult = PHAsset.fetchAssetsWithMediaType(.Image, options: fetchOptions) {
if let asset = fetchResult.firstObject as? PHAsset {
let manager = PHImageManager.defaultManager()
let targetSize = size == nil ? CGSize(width: asset.pixelWidth, height: asset.pixelHeight) : size!
manager.requestImageForAsset(asset,
targetSize: targetSize,
contentMode: .AspectFit,
options: nil,
resultHandler: { image, info in
imageCallback(image)
})
} else {
imageCallback(nil)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment