Actual Solution (swift 4 and probably swift 3):
In your viewDidLoad or where ever is right for your case call checkAuthorizationForPhotoLibraryAndGet()
private func getPhotosAndVideos(){
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate",ascending: false)]
fetchOptions.predicate = NSPredicate(format: "mediaType = %d || mediaType = %d", PHAssetMediaType.image.rawValue, PHAssetMediaType.video.rawValue)
let imagesAndVideos = PHAsset.fetchAssets(with: fetchOptions)
print(imagesAndVideos.count)
}
private func checkAuthorizationForPhotoLibraryAndGet(){
let status = PHPhotoLibrary.authorizationStatus()
if (status == PHAuthorizationStatus.authorized) {
// Access has been granted.
getPhotosAndVideos()
}else {
PHPhotoLibrary.requestAuthorization({ (newStatus) in
if (newStatus == PHAuthorizationStatus.authorized) {
self.getPhotosAndVideos()
}else {
}
})
}
}
1) Make sure mediaType = %d is used instead of mediaType == %d
2) Make sure you actually have authorization and can access the photo library, otherwise it would fail silently.