如何从库中获取所有照片

下面显示的代码就是我已经尝试过的。我希望实现的是从设备中获取所有照片。目前只有少数被提取。如何修改代码以便从设备加载所有图像?

let fetchOptions = PHFetchOptions() let collection:PHFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(.Moment, subtype: .Any, options: fetchOptions) if let first_Obj:AnyObject = collection.firstObject { self.assetCollection = first_Obj as! PHAssetCollection } 

更新了David对iOS 10+和Swift 4.x / 3.x的回答:

请求设备访问照片的权限:

将以下值添加到info.plist

隐私 – 照片库使用说明

并提供向用户显示的字符串。

请求所有图片:

 PHPhotoLibrary.requestAuthorization { status in switch status { case .authorized: let fetchOptions = PHFetchOptions() let allPhotos = PHAsset.fetchAssets(with: .image, options: fetchOptions) print("Found \(allPhotos.count) assets") case .denied, .restricted: print("Not allowed") case .notDetermined: // Should not see this when requesting print("Not determined yet") } } 

所有照片都非常简单,但您需要确保首先获得授权。 这是一些简单的代码来演示:

 PHPhotoLibrary.requestAuthorization { (status) in switch status { case .Authorized: print("Good to proceed") let fetchOptions = PHFetchOptions() let allPhotos = PHAsset.fetchAssetsWithMediaType(.Image, options: fetchOptions) print("Found \(allPhotos.count) images") case .Denied, .Restricted: print("Not allowed") case .NotDetermined: print("Not determined yet") } } 

在我的手机上,这将返回25750项。 在新的模拟器上,这应该产生5个图像。