tatsächliche Lösung (swift 4 und wahrscheinlich swift 3): In Ihrem viewDidLoad oder wo auch immer das Richtige für Ihren Fall Anruf 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) Stellen Sie sicher, media =% d verwendet anstelle von mediaType ==% d
2) Stellen Sie sicher, dass Sie tatsächlich eine Autorisierung haben und auf die Fotobibliothek zugreifen können, andernfalls würde sie im Hintergrund fehlschlagen.
verbesserte Formatierung – Kld