This is my helper for fetching image from photo library
@objc
class Fetcher: NSObject, PHPhotoLibraryChangeObserver {
private var imageManager = PHCachingImageManager()
private var fetchResult: PHFetchResult!
override init() {
let options = PHFetchOptions()
options.sortDescriptors = [ NSSortDescriptor(key: "modificationDate", ascending: true) ] // or "creationDate"
self.fetchResult = PHAsset.fetchAssetsWithMediaType(.Image, options: options)
super.init()
PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self)
}
deinit {
PHPhotoLibrary.sharedPhotoLibrary().unregisterChangeObserver(self)
}
func photoLibraryDidChange(changeInstance: PHChange) {
// Photos may call this method on a background queue; switch to the main queue to update the UI.
dispatch_async(dispatch_get_main_queue()) { [weak self] in
guard let sSelf = self else { return }
if let changeDetails = changeInstance.changeDetailsForFetchResult(sSelf.fetchResult) {
let updateBlock = { () -> Void in
self?.fetchResult = changeDetails.fetchResultAfterChanges
}
}
}
}
func requestLastCreateImage(targetSize:CGSize, completion: (UIImage) -> Void) -> Int32 {
let asset = self.fetchResult.lastObject as! PHAsset
let options = PHImageRequestOptions()
options.deliveryMode = .HighQualityFormat
return self.imageManager.requestImageForAsset(asset, targetSize: targetSize, contentMode: .AspectFill, options: options) { (image, info) in
if let image = image {
completion(image)
}
}
}
func requestPreviewImageAtIndex(index: Int, targetSize: CGSize, completion: (UIImage) -> Void) -> Int32 {
assert(index >= 0 && index < self.fetchResult.count, "Index out of bounds")
let asset = self.fetchResult[index] as! PHAsset
let options = PHImageRequestOptions()
options.deliveryMode = .HighQualityFormat
return self.imageManager.requestImageForAsset(asset, targetSize: targetSize, contentMode: .AspectFill, options: options) { (image, info) in
if let image = image {
completion(image)
}
}
}
func requestFullImageAtIndex(index: Int, completion: (UIImage) -> Void) {
assert(index >= 0 && index < self.fetchResult.count, "Index out of bounds")
let asset = self.fetchResult[index] as! PHAsset
self.imageManager.requestImageDataForAsset(asset, options: .None) { (data, dataUTI, orientation, info) -> Void in
if let data = data, image = UIImage(data: data) {
completion(image)
}
}
}
}
Usage:
let fetcher = Fetcher()
let variable = fetcher.requestLastCreateImage(CGSize(width: 300, height: 300), completion: { image in
print(image)
})