import UIKit
import Photos
class RecentImageViewController: UIViewController {
@IBOutlet weak var recentImageCollectionView: UICollectionView!
var recentImageArray : [UIImage] = []
override func viewDidLoad() {
super.viewDidLoad()
self.photoLibraryAccess()
self.recentCollectionViewSetUP()
}
private func recentCollectionViewSetUP() {
let nib = UINib(nibName: "RecentImageCollectionViewCell", bundle: nil)
self.recentImageCollectionView.register(nib, forCellWithReuseIdentifier: "cell")
self.recentImageCollectionView.dataSource = self
self.recentImageCollectionView.delegate = self
}
func photoLibraryAccess() {
PHPhotoLibrary.requestAuthorization { status in
switch status {
case .authorized:
self.fethTheRecentImagePhotoLibary()
case .denied, .restricted:
print("The user hasn't made a denied and restricted.")
case .notDetermined:
print("The user hasn't made a decision yet.")
case .limited:
print("This limit cross.")
@unknown default:
break
}
}
}
private func fethTheRecentImagePhotoLibary () {
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key:"creationDate", ascending: false)]
fetchOptions.fetchLimit = 30
let fetchResult: PHFetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fetchOptions)
DispatchQueue.main.async {
if fetchResult.count > 0 {
let totalImageCountNeeded = 30
self.fetchPhotoAtIndex(0, totalImageCountNeeded, fetchResult)
}
}
}
private func fetchPhotoAtIndex(_ index:Int, _ totalImageCountNeeded: Int, _ fetchResult: PHFetchResult<PHAsset>) {
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = true
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 {
self.recentImageArray += [image]
}
if index + 1 < fetchResult.count && self.recentImageArray.count < totalImageCountNeeded {
self.fetchPhotoAtIndex(index + 1, totalImageCountNeeded, fetchResult)
} else {
self.recentImageCollectionView.reloadData()
}
})
}
}