Created
September 5, 2016 08:43
-
-
Save vaghul/1ce8f9150b9c48ee1a9f4f25ab0e553b to your computer and use it in GitHub Desktop.
Snippet to get the last taken photo in iOS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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