I am trying to display a collection view of photo albums on the device. I am able to get the title but not sure how to get the Albums photo and set to the cell.
This is what I have:
import UIKit
import Photos
class PhotoAlbumViewController: UICollectionViewController {
var albumList: PHFetchResult<PHAssetCollection>! = nil
override func viewDidLoad() {
super.viewDidLoad()
albumList = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: nil)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
albumList.count
}
override func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
let album = albumList.object(at: indexPath.row)
if let label = cell.viewWithTag(4000) as? UILabel {
label.text = album.localizedTitle
}
}
}
I have a UI Label in my storyboard and label.text = album.localizedTitle sets the Album title correctly. Not sure how to get the image and set it to my Image component.
You can try this to get all ALBUM names from Photo Library
func get_All_Albums()
{
DispatchQueue.global(qos: .userInteractive).async
{
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)
let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .any, options: nil)
let customAlbums = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: nil)
[smartAlbums, customAlbums].forEach {
$0.enumerateObjects { collection, index, stop in
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = true
requestOptions.deliveryMode = .highQualityFormat
let photoInAlbum = PHAsset.fetchAssets(in: collection, options: fetchOptions)
if let title = collection.localizedTitle
{
if photoInAlbum.count > 0
{
print("\n\n \(title) --- count = \(photoInAlbum.count) \n\n")
}
}
}
}
}
}
& try this to get Photos from a specific Album
func get_Photos_From_Album(albumName: String)
{
var photoLibraryImages = [UIImage]()
var photoLibraryAssets = [PHAsset]()
//whatever you need, you can use UIImage or PHAsset to photos in UICollectionView
DispatchQueue.global(qos: .userInteractive).async
{
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)
let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .any, options: nil)
let customAlbums = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: nil)
[smartAlbums, customAlbums].forEach {
$0.enumerateObjects { collection, index, stop in
let imgManager = PHImageManager.default()
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = true
requestOptions.deliveryMode = .highQualityFormat
let photoInAlbum = PHAsset.fetchAssets(in: collection, options: fetchOptions)
if let title = collection.localizedTitle
{
if photoInAlbum.count > 0
{
print("\n\n \(title) --- count = \(photoInAlbum.count) \n\n")
}
if title == albumName
{
if photoInAlbum.count > 0
{
for i in (0..<photoInAlbum.count).reversed()
{
imgManager.requestImage(for: photoInAlbum.object(at: i) as PHAsset , targetSize: CGSize(width: 150, height: 150), contentMode: .aspectFit, options: requestOptions, resultHandler: {
image, error in
if image != nil
{
photoLibraryImages.append(image!)
photoLibraryAssets.append(photoInAlbum.object(at: i))
}
})
}
}
}
}
}
}
}
}
I am loading the photos from a users photo album into a collection view similar to how is done in this Apple Sample project. I can not seem to track down why the memory is growing out of control. I use the suggested PHCachingImageManager but all that results are blurry images, freezing scrolling and memory growing out of control until the application crashes.
In my viewDidLoad I run the code below
PHPhotoLibrary.requestAuthorization { (status: PHAuthorizationStatus) in
print("photo authorization status: \(status)")
if status == .authorized && self.fetchResult == nil {
print("authorized")
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
var tempArr:[PHAsset] = []
self.fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
guard let fetchResult = self.fetchResult else{
print("Fetch result is empty")
return
}
fetchResult.enumerateObjects({asset, index, stop in
tempArr.append(asset)
})
// self.assets = tempArr
self.imageManager.startCachingImages(for: tempArr, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFill, options: nil)
tempArr.removeAll()
print("Asset count after initial fetch: \(self.assets?.count)")
DispatchQueue.main.async {
// Reload collection view once we've determined our Photos permissions.
print("inside of main queue reload")
PHPhotoLibrary.shared().register(self)
self.collectionView.delegate = self
self.collectionView.dataSource = self
self.collectionView.reloadData()
}
} else {
print("photo access denied")
self.displayPhotoAccessDeniedAlert()
}
}
and inside of cellForItemAt: I run the following code
cellForItemAt
guard let fetchResult = self.fetchResult else{
print("Fetch Result is empty")
return UICollectionViewCell()
}
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = false
requestOptions.deliveryMode = .highQualityFormat
//let scale = min(2.0, UIScreen.main.scale)
let scale = UIScreen.main.scale
let targetSize = CGSize(width: cell.bounds.width * scale, height: cell.bounds.height * scale)
// let asset = assets[indexPath.item]
let asset = fetchResult.object(at: indexPath.item)
let assetIdentifier = asset.localIdentifier
cell.representedAssetIdentifier = assetIdentifier
imageManager.requestImage(for: asset, targetSize: cell.frame.size,
contentMode: .aspectFill, options: requestOptions) { (image, hashable) in
if let loadedImage = image, let cellIdentifier = cell.representedAssetIdentifier {
// Verify that the cell still has the same asset identifier,
// so the image in a reused cell is not overwritten.
if cellIdentifier == assetIdentifier {
cell.imageView.image = loadedImage
}
}
}
I had a similar problem this week using the Apple Code which for others reference is available here Browsing & Modifying Photos
Memory usage was very high, and then if viewing a single item and returning to root, memory would spike and the example would crash.
As such from our experiments there were a few tweaks which improved performance.
Firstly when setting the thumbnailSize for the requestImage function:
open func requestImage(for asset: PHAsset, targetSize: CGSize, contentMode: PHImageContentMode, options: PHImageRequestOptions?, resultHandler: #escaping (UIImage?, [AnyHashable : Any]?) -> Void) -> PHImageRequestID
We set the scale like so instead of using the full size:
UIScreen.main.scale * 0.75
We also set the PHImageRequestOptions Resizing Mode to .fast.
As well as this we found that setting the following variables of the CollectionViewCell also helped somewhat:
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
isOpaque = true
We also noticed that the updateCachedAssets() in the ScrollViewwDidScroll method was playing some part in this process so we removed that from this callback(rightly or wrongly).
And one final thing was the we kept a reference to the PHCachingImageManager for each cell and if it existed then we called:
open func cancelImageRequest(_ requestID: PHImageRequestID)
As such here is the code for our MediaCell:
extension MediaCell{
/// Populates The Cell From The PHAsset Data
///
/// - Parameter asset: PHAsset
func populateCellFrom(_ asset: PHAsset){
livePhotoBadgeImage = asset.mediaSubtypes.contains(.photoLive) ? PHLivePhotoView.livePhotoBadgeImage(options: .overContent) : nil
videoDuration = asset.mediaType == .video ? asset.duration.formattedString() : ""
representedAssetIdentifier = asset.localIdentifier
}
/// Shows The Activity Indicator When Downloading From The Cloud
func startAnimator(){
DispatchQueue.main.async {
self.activityIndicator.isHidden = false
self.activityIndicator.startAnimating()
}
}
/// Hides The Activity Indicator After The ICloud Asset Has Downloaded
func endAnimator(){
DispatchQueue.main.async {
self.activityIndicator.isHidden = true
self.activityIndicator.stopAnimating()
}
}
}
final class MediaCell: UICollectionViewCell, Animatable {
#IBOutlet private weak var imageView: UIImageView!
#IBOutlet private weak var livePhotoBadgeImageView: UIImageView!
#IBOutlet private weak var videoDurationLabel: UILabel!
#IBOutlet weak var activityIndicator: UIActivityIndicatorView!{
didSet{
activityIndicator.isHidden = true
}
}
var representedAssetIdentifier: String!
var requestIdentifier: PHImageRequestID!
var thumbnailImage: UIImage! {
didSet {
imageView.image = thumbnailImage
}
}
var livePhotoBadgeImage: UIImage! {
didSet {
livePhotoBadgeImageView.image = livePhotoBadgeImage
}
}
var videoDuration: String!{
didSet{
videoDurationLabel.text = videoDuration
}
}
//----------------
//MARK:- LifeCycle
//----------------
override func awakeFromNib() {
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
isOpaque = true
}
override func prepareForReuse() {
super.prepareForReuse()
imageView.image = nil
representedAssetIdentifier = ""
requestIdentifier = nil
livePhotoBadgeImageView.image = nil
videoDuration = ""
activityIndicator.isHidden = true
activityIndicator.stopAnimating()
}
}
And the code for the cellForItem:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let asset = dataViewModel.assettAtIndexPath(indexPath)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "mediaCell", for: indexPath) as! MediaCell
if let requestID = cell.requestIdentifier { imageManager.cancelImageRequest(requestID) }
cell.populateCellFrom(asset)
let options = PHImageRequestOptions()
options.resizeMode = .fast
options.isNetworkAccessAllowed = true
options.progressHandler = { (progress, error, stop, info) in
if progress == 0.0{
cell.startAnimator()
} else if progress == 1.0{
cell.endAnimator()
}
}
cell.requestIdentifier = imageManager.requestImage(for: asset, targetSize: thumbnailSize,
contentMode: .aspectFill, options: options,
resultHandler: { image, info in
if cell.representedAssetIdentifier == asset.localIdentifier {
cell.thumbnailImage = image
}
})
return cell
}
One additional area is in the updateCachedAssets() funtion. You are using:
self.imageManager.startCachingImages(for: tempArr, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFill, options: nil)
It would probably be best to set a smaller size here e.g:
imageManager.startCachingImages(for: addedAssets,
targetSize: thumbnailSize, contentMode: .aspectFill, options: nil)
Whereby thumbnail size e.g:
/// Sets The Thumnail Image Size
private func setupThumbnailSize(){
let scale = isIpad ? UIScreen.main.scale : UIScreen.main.scale * 0.75
let cellSize = collectionViewFlowLayout.itemSize
thumbnailSize = CGSize(width: cellSize.width * scale, height: cellSize.height * scale)
}
All of these tweaks helped to ensure that the memory usage remained fair constant, and in our testing ensured that there were no exceptions thrown.
Hope it helps.
I am using below code for getting videos(URL, Durations, Thumbnails). After Fetching data i am displaying it on CollectionView.
The main problem is that, some video and its thumbnails not match each other. Can any one please tell me how i can fix it, or any other better solution?
Thanks
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
cell.imgV.image = photoLibrary[indexPath.row]
let duration: TimeInterval = videosDuration[indexPath.row] // 2 minutes, 30 seconds
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.allowedUnits = [ .minute, .second ]
formatter.zeroFormattingBehavior = [ .pad ]
let formattedDuration = formatter.string(from: duration)
cell.duration.text = "\(String(describing: formattedDuration!))"
return cell
}
func grabPhotos(){
let imgManager = PHImageManager.default()
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = false
requestOptions.deliveryMode = .highQualityFormat
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
if let fetchResult : PHFetchResult = PHAsset.fetchAssets(with: .video, options: fetchOptions) {
if fetchResult.count > 0 {
for i in 0..<fetchResult.count{
//Used for fetch Image//
imgManager.requestImage(for: fetchResult.object(at: i) as PHAsset , targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFill, options: requestOptions, resultHandler: {
image, error in
let imageOfVideo = image! as UIImage
self.photoLibrary.append(imageOfVideo)
})
//Used for fetch Video//
imgManager.requestAVAsset(forVideo: fetchResult.object(at: i) as PHAsset, options: PHVideoRequestOptions(), resultHandler: {(avAsset, audioMix, info) -> Void in
if let asset = avAsset as? AVURLAsset {
self.videoURL.append(asset.url)
let duration : CMTime = asset.duration
let durationInSecond = CMTimeGetSeconds(duration)
self.videosDuration.append(durationInSecond)
}
})
}
}
else{
//showAllertToImportImage()//A function to show alert
}
}
}
Since photos are being fetched asynchronously so the order is not maintained in the images and videos array, so to get the corresponding image for the video you can use dictionaries to store the result
I have made some modifications in your code, please check
var imageDictionary = [String: AnyObject]()
var videoDictionary = [String: AnyObject]()
func fetchData(){
let imgManager = PHImageManager.default()
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = false
requestOptions.deliveryMode = .highQualityFormat
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
if let fetchResult : PHFetchResult = PHAsset.fetchAssets(with: .video, options: fetchOptions) {
if fetchResult.count > 0 {
for i in 0..<fetchResult.count{
//Used for fetch Image//
imgManager.requestImage(for: fetchResult.object(at: i) as PHAsset , targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFill, options: requestOptions, resultHandler: {
image, error in
let imageOfVideo = image! as UIImage
//self.photoLibrary.append(imageOfVideo)
let key = "\(i)"
self.imageDictionary[key] = imageOfVideo
})
//Used for fetch Video//
imgManager.requestAVAsset(forVideo: fetchResult.object(at: i) as PHAsset, options: PHVideoRequestOptions(), resultHandler: {(avAsset, audioMix, info) -> Void in
if let asset = avAsset as? AVURLAsset {
//let videoData = NSData(contentsOf: asset.url)
self.videoURL.append(asset.url)
//print(asset.url)
let duration : CMTime = asset.duration
let durationInSecond = CMTimeGetSeconds(duration)
//self.videosDuration.append(durationInSecond)
//print(durationInSecond)
let key = "\(i)"
self.videoDictionary[key] = ["VideoURL" : asset.url, "VideoDuration" : durationInSecond]
}
})
}
}
else{
//showAllertToImportImage()//A function to show alert
}
}
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.imageDictionary.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//You can access the values like this....
let key = "\(indexPath.row)"
cell.image = self.imageDictionary[key] as? UIImage
let singleVideo = self.videoDictionary[key] as? [String: AnyObject]
cell.videoURL = singleVideo["VideoURL"] as? URL
cell.videoDuration = singleVideo["VideoDuration"] as? CMTime
}
I need get all photo albums from device. I use this code for fetch albums:
func fetchAlbums() {
// Get all user albums
let userAlbumsOptions = PHFetchOptions()
userAlbumsOptions.predicate = NSPredicate(format: "estimatedAssetCount > 0")
let userAlbums = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.album, subtype: PHAssetCollectionSubtype.any, options: userAlbumsOptions)
userAlbums.enumerateObjects( {
if let collection = $0.0 as? PHAssetCollection {
print("album title: \(collection.localizedTitle)")
let onlyImagesOptions = PHFetchOptions()
onlyImagesOptions.predicate = NSPredicate(format: "mediaType = %i", PHAssetMediaType.image.rawValue)
if let result = PHAsset.fetchKeyAssets(in: collection, options: onlyImagesOptions) {
print("Images count: \(result.count)")
if result.count > 0 {
//Add album titie
self.albumsTitles.append(collection.localizedTitle!)
//Add album
self.albumsArray.append(result as! PHFetchResult<AnyObject>)
}
}
}
} )
}
But i can't get all photos. All albums without photos from iCloud library, only local photos.
I use Collection View for preview photo. Example my code for fetch photos from selected album:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: AlbumPhotoCollectionViewCell.self),
for: indexPath as IndexPath) as! AlbumPhotoCollectionViewCell
//Array with albums
let asset = self.albumsArray[indexSelectedAlbum]
let album = asset[indexPath.item]
let options = PHImageRequestOptions()
options.isNetworkAccessAllowed = true
PHImageManager.default().requestImage(for: album as! PHAsset ,
targetSize: self.assetThumbnailSize,
contentMode: .aspectFill,
options: options,
resultHandler: {(result, info)in
if result != nil {
cell.albumPhoto.image = result
}
})
return cell
}
I change fetch and all working.
Old code:
if let result = PHAsset.fetchKeyAssets(in: collection, options: onlyImagesOptions){
//Code
}
New code
let result = PHAsset.fetchAssets(in: collection, options: onlyImagesOptions)
I need to get and show last taken 3 photos from photo library on viewDidload event without any clicks.
After this step, I should get other photos 3 by 3 when I scroll the ScrollView.
Do you know the proper way to do this with swift? Thanks.
Here's a solution using the Photos framework available for devices iOS 8+ :
import Photos
class ViewController: UIViewController {
var images:[UIImage] = []
func fetchPhotos () {
// Sort the images by descending creation date and fetch the first 3
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key:"creationDate", ascending: false)]
fetchOptions.fetchLimit = 3
// Fetch the image assets
let fetchResult: PHFetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fetchOptions)
// If the fetch result isn't empty,
// proceed with the image request
if fetchResult.count > 0 {
let totalImageCountNeeded = 3 // <-- The number of images to fetch
fetchPhotoAtIndex(0, totalImageCountNeeded, fetchResult)
}
}
// Repeatedly call the following method while incrementing
// the index until all the photos are fetched
func fetchPhotoAtIndex(_ index:Int, _ totalImageCountNeeded: Int, _ fetchResult: PHFetchResult<PHAsset>) {
// Note that if the request is not set to synchronous
// the requestImageForAsset will return both the image
// and thumbnail; by setting synchronous to true it
// will return just the thumbnail
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = true
// Perform the image request
PHImageManager.default().requestImage(for: fetchResult.object(at: index) as PHAsset, targetSize: view.frame.size, contentMode: PHImageContentMode.aspectFill, options: requestOptions, resultHandler: { (image, _) in
if let image = image {
// Add the returned image to your array
self.images += [image]
}
// If you haven't already reached the first
// index of the fetch result and if you haven't
// already stored all of the images you need,
// perform the fetch request again with an
// incremented index
if index + 1 < fetchResult.count && self.images.count < totalImageCountNeeded {
self.fetchPhotoAtIndex(index + 1, totalImageCountNeeded, fetchResult)
} else {
// Else you have completed creating your array
print("Completed array: \(self.images)")
}
})
}
}
Details
Xcode 10.2 (10E125), Swift 5
Solution features
works in asynchronously and thread/queue safety
get albums ( + all photos album)
optimized for fast scrolling
get images with defined size
Info.plist
Add to Info.plist
<key>NSPhotoLibraryUsageDescription</key>
<string>{bla-bla-bla}</string>
Solution
AtomicArray here: https://stackoverflow.com/a/54565351/4488252
import UIKit
import Photos
enum PhotoAlbumViewModel {
case regular(id: Int, title: String, count: Int, image: UIImage, isSelected: Bool)
case allPhotos(id: Int, title: String, count: Int, image: UIImage, isSelected: Bool)
var id: Int { switch self { case .regular(let params), .allPhotos(let params): return params.id } }
var count: Int { switch self { case .regular(let params), .allPhotos(let params): return params.count } }
var title: String { switch self { case .regular(let params), .allPhotos(let params): return params.title } }
}
class PhotoService {
internal lazy var imageManager = PHCachingImageManager()
private lazy var queue = DispatchQueue(label: "PhotoService_queue",
qos: .default, attributes: .concurrent,
autoreleaseFrequency: .workItem, target: nil)
private lazy var getImagesQueue = DispatchQueue(label: "PhotoService_getImagesQueue",
qos: .userInteractive, attributes: [],
autoreleaseFrequency: .inherit, target: nil)
private lazy var thumbnailSize = CGSize(width: 200, height: 200)
private lazy var imageAlbumsIds = AtomicArray<Int>()
private let getImageSemaphore = DispatchSemaphore(value: 12)
typealias AlbumData = (fetchResult: PHFetchResult<PHAsset>, assetCollection: PHAssetCollection?)
private let _cachedAlbumsDataSemaphore = DispatchSemaphore(value: 1)
private lazy var _cachedAlbumsData = [Int: AlbumData]()
deinit {
print("____ PhotoServiceImpl deinited")
imageManager.stopCachingImagesForAllAssets()
}
}
// albums
extension PhotoService {
private func getAlbumData(id: Int, completion: ((AlbumData?) -> Void)?) {
_ = _cachedAlbumsDataSemaphore.wait(timeout: .now() + .seconds(3))
if let cachedAlbum = _cachedAlbumsData[id] {
completion?(cachedAlbum)
_cachedAlbumsDataSemaphore.signal()
return
} else {
_cachedAlbumsDataSemaphore.signal()
}
var result: AlbumData? = nil
switch id {
case 0:
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
let allPhotos = PHAsset.fetchAssets(with: .image, options: fetchOptions)
result = (allPhotos, nil)
default:
let collections = getAllAlbumsAssetCollections()
let id = id - 1
if id < collections.count {
_fetchAssets(in: collections[id]) { fetchResult in
result = (fetchResult, collections[id])
}
}
}
guard let _result = result else { completion?(nil); return }
_ = _cachedAlbumsDataSemaphore.wait(timeout: .now() + .seconds(3))
_cachedAlbumsData[id] = _result
_cachedAlbumsDataSemaphore.signal()
completion?(_result)
}
private func getAllAlbumsAssetCollections() -> PHFetchResult<PHAssetCollection> {
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "endDate", ascending: true)]
fetchOptions.predicate = NSPredicate(format: "estimatedAssetCount > 0")
return PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
}
func getAllAlbums(completion: (([PhotoAlbumViewModel])->Void)?) {
queue.async { [weak self] in
guard let self = self else { return }
var viewModels = AtomicArray<PhotoAlbumViewModel>()
var allPhotosAlbumViewModel: PhotoAlbumViewModel?
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
self.getAlbumData(id: 0) { data in
guard let data = data, let asset = data.fetchResult.lastObject else { dispatchGroup.leave(); return }
self._fetchImage(from: asset, userInfo: nil, targetSize: self.thumbnailSize,
deliveryMode: .fastFormat, resizeMode: .fast) { [weak self] (image, _) in
guard let self = self, let image = image else { dispatchGroup.leave(); return }
allPhotosAlbumViewModel = .allPhotos(id: 0, title: "All Photos",
count: data.fetchResult.count,
image: image, isSelected: false)
self.imageAlbumsIds.append(0)
dispatchGroup.leave()
}
}
let numberOfAlbums = self.getAllAlbumsAssetCollections().count + 1
for id in 1 ..< numberOfAlbums {
dispatchGroup.enter()
self.getAlbumData(id: id) { [weak self] data in
guard let self = self else { return }
guard let assetCollection = data?.assetCollection else { dispatchGroup.leave(); return }
self.imageAlbumsIds.append(id)
self.getAlbumViewModel(id: id, collection: assetCollection) { [weak self] model in
guard let self = self else { return }
defer { dispatchGroup.leave() }
guard let model = model else { return }
viewModels.append(model)
}
}
}
_ = dispatchGroup.wait(timeout: .now() + .seconds(3))
var _viewModels = [PhotoAlbumViewModel]()
if let allPhotosAlbumViewModel = allPhotosAlbumViewModel {
_viewModels.append(allPhotosAlbumViewModel)
}
_viewModels += viewModels.get()
DispatchQueue.main.async { completion?(_viewModels) }
}
}
private func getAlbumViewModel(id: Int, collection: PHAssetCollection, completion: ((PhotoAlbumViewModel?) -> Void)?) {
_fetchAssets(in: collection) { [weak self] fetchResult in
guard let self = self, let asset = fetchResult.lastObject else { completion?(nil); return }
self._fetchImage(from: asset, userInfo: nil, targetSize: self.thumbnailSize,
deliveryMode: .fastFormat, resizeMode: .fast) { (image, nil) in
guard let image = image else { completion?(nil); return }
completion?(.regular(id: id,
title: collection.localizedTitle ?? "",
count: collection.estimatedAssetCount,
image: image, isSelected: false))
}
}
}
}
// fetch
extension PhotoService {
fileprivate func _fetchImage(from photoAsset: PHAsset,
userInfo: [AnyHashable: Any]? = nil,
targetSize: CGSize, //= PHImageManagerMaximumSize,
deliveryMode: PHImageRequestOptionsDeliveryMode = .fastFormat,
resizeMode: PHImageRequestOptionsResizeMode,
completion: ((_ image: UIImage?, _ userInfo: [AnyHashable: Any]?) -> Void)?) {
// guard authorizationStatus() == .authorized else { completion(nil); return }
let options = PHImageRequestOptions()
options.resizeMode = resizeMode
options.isSynchronous = true
options.deliveryMode = deliveryMode
imageManager.requestImage(for: photoAsset,
targetSize: targetSize,
contentMode: .aspectFill,
options: options) { (image, info) -> Void in
guard let info = info,
let isImageDegraded = info[PHImageResultIsDegradedKey] as? Int,
isImageDegraded == 0 else { completion?(nil, nil); return }
completion?(image, userInfo)
}
}
private func _fetchAssets(in collection: PHAssetCollection, completion: #escaping (PHFetchResult<PHAsset>) -> Void) {
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
let assets = PHAsset.fetchAssets(in: collection, options: fetchOptions)
completion(assets)
}
private func fetchImage(from asset: PHAsset,
userInfo: [AnyHashable: Any]?,
targetSize: CGSize,
deliveryMode: PHImageRequestOptionsDeliveryMode,
resizeMode: PHImageRequestOptionsResizeMode,
completion: ((UIImage?, _ userInfo: [AnyHashable: Any]?) -> Void)?) {
queue.async { [weak self] in
self?._fetchImage(from: asset, userInfo: userInfo, targetSize: targetSize,
deliveryMode: deliveryMode, resizeMode: resizeMode) { (image, _) in
DispatchQueue.main.async { completion?(image, userInfo) }
}
}
}
func getImage(albumId: Int, index: Int,
userInfo: [AnyHashable: Any]?,
targetSize: CGSize,
deliveryMode: PHImageRequestOptionsDeliveryMode,
resizeMode: PHImageRequestOptionsResizeMode,
completion: ((_ image: UIImage?, _ userInfo: [AnyHashable: Any]?) -> Void)?) {
getImagesQueue.async { [weak self] in
guard let self = self else { return }
let indexPath = IndexPath(item: index, section: albumId)
self.getAlbumData(id: albumId) { data in
_ = self.getImageSemaphore.wait(timeout: .now() + .seconds(3))
guard let photoAsset = data?.fetchResult.object(at: index) else { self.getImageSemaphore.signal(); return }
self.fetchImage(from: photoAsset,
userInfo: userInfo,
targetSize: targetSize,
deliveryMode: deliveryMode,
resizeMode: resizeMode) { [weak self] (image, userInfo) in
defer { self?.getImageSemaphore.signal() }
completion?(image, userInfo)
}
}
}
}
}
Usage
private lazy var photoLibrary = PhotoService()
private var albums = [PhotoAlbumViewModel]()
//....
// Get albums
photoLibrary.getAllAlbums { [weak self] albums in
self?.albums = albums
// reload views
}
// Get photo
photoLibrary.getImage(albumId: albums[0].id,
index: 1, userInfo: nil,
targetSize: CGSize(width: 200, height: 200),
deliveryMode: .fastFormat,
resizeMode: .fast) { [weak self, weak cell] (image, userInfo) in
// reload views
}
Full Sample (collectionView with images from PhotoLibrary)
ViewController.swift
import UIKit
import Photos
class ViewController: UIViewController {
private weak var collectionView: UICollectionView?
var collectionViewFlowLayout: UICollectionViewFlowLayout? {
return collectionView?.collectionViewLayout as? UICollectionViewFlowLayout
}
private lazy var photoLibrary = PhotoService()
private lazy var numberOfElementsInRow = 4
private lazy var cellIdentifier = "cellIdentifier"
private lazy var supplementaryViewIdentifier = "supplementaryViewIdentifier"
private var albums = [PhotoAlbumViewModel]()
private lazy var cellsTags = [IndexPath: Int]()
private lazy var tagKey = "cellTag"
private lazy var thumbnailImageSize = CGSize(width: 200, height: 200)
override func viewDidLoad() {
let collectionViewFlowLayout = UICollectionViewFlowLayout()
collectionViewFlowLayout.minimumLineSpacing = 5
collectionViewFlowLayout.minimumInteritemSpacing = 5
let _numberOfElementsInRow = CGFloat(numberOfElementsInRow)
let allWidthBetwenCells = _numberOfElementsInRow == 0 ? 0 : collectionViewFlowLayout.minimumInteritemSpacing*(_numberOfElementsInRow-1)
let width = (view.frame.width - allWidthBetwenCells)/_numberOfElementsInRow
collectionViewFlowLayout.itemSize = CGSize(width: width, height: width)
collectionViewFlowLayout.headerReferenceSize = CGSize(width: 0, height: 40)
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionViewFlowLayout)
view.addSubview(collectionView)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
collectionView.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor).isActive = true
collectionView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor).isActive = true
collectionView.register(CollectionViewCell.self, forCellWithReuseIdentifier: cellIdentifier)
collectionView.register(SupplementaryView.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: supplementaryViewIdentifier)
collectionView.backgroundColor = .white
self.collectionView = collectionView
collectionView.delegate = self
showAllPhotosButtonTouchedInside()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "All", style: .done, target: self,
action: #selector(showAllPhotosButtonTouchedInside))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "last 3", style: .done, target: self,
action: #selector(showLastSeveralPhotosButtonTouchedInside))
}
#objc func showAllPhotosButtonTouchedInside() {
photoLibrary.getAllAlbums { [weak self] albums in
self?.set(albums: albums)
if self?.collectionView?.dataSource == nil {
self?.collectionView?.dataSource = self
} else {
self?.collectionView?.reloadData()
}
}
}
#objc func showLastSeveralPhotosButtonTouchedInside() {
photoLibrary.getAllAlbums { [weak self] albums in
guard let firstAlbum = albums.first else { return }
var album: PhotoAlbumViewModel!
let maxPhotosToDisplay = 3
switch firstAlbum {
case .allPhotos(let id, let title, let count, let image, let isSelected):
let newCount = count > maxPhotosToDisplay ? maxPhotosToDisplay : count
album = .allPhotos(id: id, title: title, count: newCount, image: image, isSelected: isSelected)
case .regular(let id, let title, let count, let image, let isSelected):
let newCount = count > maxPhotosToDisplay ? maxPhotosToDisplay : count
album = .regular(id: id, title: title, count: newCount, image: image, isSelected: isSelected)
}
self?.set(albums: [album])
if self?.collectionView?.dataSource == nil {
self?.collectionView?.dataSource = self
} else {
self?.collectionView?.reloadData()
}
}
}
private func set(albums: [PhotoAlbumViewModel]) {
self.albums = albums
var counter = 0
for (section, album) in albums.enumerated() {
for row in 0..<album.count {
self.cellsTags[IndexPath(row: row, section: section)] = counter
counter += 1
}
}
}
}
extension ViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int { return albums.count }
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return albums[section].count
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: supplementaryViewIdentifier, for: indexPath) as! SupplementaryView
header.label?.text = albums[indexPath.section].title
return header
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! CollectionViewCell
let tag = cellsTags[indexPath]!
cell.tag = tag
photoLibrary.getImage(albumId: albums[indexPath.section].id,
index: indexPath.item, userInfo: [tagKey: tag],
targetSize: thumbnailImageSize,
deliveryMode: .fastFormat,
resizeMode: .fast) { [weak self, weak cell] (image, userInfo) in
guard let cell = cell, let tagKey = self?.tagKey,
let cellTag = userInfo?[tagKey] as? Int,
cellTag == cell.tag else { return }
cell.imageView?.image = image
}
return cell
}
}
extension ViewController: UICollectionViewDelegate {}
CollectionViewCell.swift
import UIKit
class CollectionViewCell: UICollectionViewCell {
weak var imageView: UIImageView?
override init(frame: CGRect) {
super.init(frame: frame)
clipsToBounds = true
let imageView = UIImageView(frame: .zero)
imageView.contentMode = .scaleAspectFill
addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.topAnchor.constraint(equalTo: topAnchor).isActive = true
imageView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
imageView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true
imageView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
self.imageView = imageView
backgroundColor = UIColor.lightGray.withAlphaComponent(0.3)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func prepareForReuse() {
super.prepareForReuse()
imageView?.image = nil
}
}
SupplementaryView.swift
import UIKit
class SupplementaryView: UICollectionReusableView {
weak var label: UILabel?
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
let label = UILabel(frame: frame)
label.textColor = .black
addSubview(label)
self.label = label
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func prepareForReuse() {
super.prepareForReuse()
self.label?.text = nil
}
}
Storyboard
Results
Here's an elegant solution with efficiency in Swift 4.
In short, we request the latest photo assets once, then convert them into image when needed.
First import Photos Library:
import Photos
Then create a function to fetch the lastest photos taken:
func fetchLatestPhotos(forCount count: Int?) -> PHFetchResult<PHAsset> {
// Create fetch options.
let options = PHFetchOptions()
// If count limit is specified.
if let count = count { options.fetchLimit = count }
// Add sortDescriptor so the lastest photos will be returned.
let sortDescriptor = NSSortDescriptor(key: "creationDate", ascending: false)
options.sortDescriptors = [sortDescriptor]
// Fetch the photos.
return PHAsset.fetchAssets(with: .image, options: options)
}
In your case you might want to fetch enough photos at once (for example 50), then store the result somewhere in your view controller:
var latestPhotoAssetsFetched: PHFetchResult<PHAsset>? = nil
In viewDidLoad:
self.latestPhotoAssetsFetched = self.fetchLatestPhotos(forCount: 50)
Finally request the image at the right place (for example, a collection view cell):
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
/*
...your code to configure the cell...
*/
// Get the asset. If nothing, return the cell.
guard let asset = self.latestPhotoAssetsFetched?[indexPath.item] else {
return cell
}
// Here we bind the asset with the cell.
cell.representedAssetIdentifier = asset.localIdentifier
// Request the image.
PHImageManager.default().requestImage(for: asset,
targetSize: cell.imageView.frame.size,
contentMode: .aspectFill,
options: nil) { (image, _) in
// By the time the image is returned, the cell may has been recycled.
// We update the UI only when it is still on the screen.
if cell.representedAssetIdentifier == asset.localIdentifier {
cell.imageView.image = image
}
}
return cell
}
Remember to add a property to your cell:
class PhotoCell: UICollectionViewCell {
var representedAssetIdentifier: String? = nil
}
You can extract the 3 latest photos using functions in the AssetsLibrary framework. First you have to add the framework to the project. The following function retrieves the 3 latest photos and calls the completion block.
import AssetsLibrary
func getLatestPhotos(completion completionBlock : ([UIImage] -> ())) {
let library = ALAssetsLibrary()
var count = 0
var images : [UIImage] = []
var stopped = false
library.enumerateGroupsWithTypes(ALAssetsGroupSavedPhotos, usingBlock: { (group,var stop) -> Void in
group?.setAssetsFilter(ALAssetsFilter.allPhotos())
group?.enumerateAssetsWithOptions(NSEnumerationOptions.Reverse, usingBlock: {
(asset : ALAsset!, index, var stopEnumeration) -> Void in
if (!stopped)
{
if count >= 3
{
stopEnumeration.memory = ObjCBool(true)
stop.memory = ObjCBool(true)
completionBlock(images)
stopped = true
}
else
{
// For just the thumbnails use the following line.
let cgImage = asset.thumbnail().takeUnretainedValue()
// Use the following line for the full image.
let cgImage = asset.defaultRepresentation().fullScreenImage().takeUnretainedValue()
if let image = UIImage(CGImage: cgImage) {
images.append(image)
count += 1
}
}
}
})
},failureBlock : { error in
println(error)
})
}
The above function can be called like this
getLatestPhotos(completion: { images in
println(images)
//Set Images in this block.
})
Here is #Lindsey Scott's answer but in Objective-C. I am putting the last 9 photos from Camera Roll into a collection view:
-(void)fetchPhotoFromEndAtIndex:(int)index{
PHImageRequestOptions *options = [[PHImageRequestOptions alloc]init];
options.synchronous = YES;
PHFetchOptions *fetchOptions = [[PHFetchOptions alloc]init];
fetchOptions.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"creationDate" ascending:YES]];
PHFetchResult *photos = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
if (photos) {
[[PHImageManager defaultManager] requestImageForAsset:[photos objectAtIndex:photos.count -1 -index] targetSize:CGSizeMake(self.collectionView.frame.size.width/3, self.collectionView.frame.size.height/3) contentMode:PHImageContentModeAspectFill options:options resultHandler:^(UIImage *result, NSDictionary *info) {
[self.imagesArray addObject:result];
if (index + 1 < photos.count && self.imagesArray.count < 9) {
[self fetchPhotoFromEndAtIndex:index + 1];
}
}];
}
[self.collectionView reloadData];
}