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
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 {
// 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? = 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
}