19

我试图从图书馆获取照片。它有效,但我只从图书馆的 9 张照片中获得了 3 张照片。这是我的代码:

let options = PHFetchOptions()
    let userAlbums = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.album, subtype: PHAssetCollectionSubtype.any, options: options)

    let userPhotos = PHAsset.fetchKeyAssets(in: userAlbums.firstObject!, options: nil)
    let imageManager = PHCachingImageManager()

    userPhotos?.enumerateObjects({ (object: AnyObject!, count: Int, stop: UnsafeMutablePointer) in
        if object is PHAsset {
            let obj:PHAsset = object as! PHAsset

            let fetchOptions = PHFetchOptions()
            fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
            fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)

            let options = PHImageRequestOptions()
            options.deliveryMode = .fastFormat
            options.isSynchronous = true

            imageManager.requestImage(for: obj, targetSize: CGSize(width: obj.pixelWidth, height: obj.pixelHeight), contentMode: .aspectFill, options: options, resultHandler: { img, info in

                self.images.append(img!)
            })
        }
    })

当我尝试images.count时,它说 3. 谁能帮我找出我的错误并获取所有照片?非常感谢!

4

3 回答 3

31

尝试这个,

首先导入照片

import Photos

然后在 viewDidLoad() 之前声明存储照片的数组

var allPhotos : PHFetchResult<PHAsset>? = nil

现在在 viewDidLoad() 中编写获取照片的代码

    /// Load Photos
    PHPhotoLibrary.requestAuthorization { (status) in
        switch status {
        case .authorized:
            print("Good to proceed")
            let fetchOptions = PHFetchOptions()
            self.allPhotos = PHAsset.fetchAssets(with: .image, options: fetchOptions)
        case .denied, .restricted:
            print("Not allowed")
        case .notDetermined:
            print("Not determined yet")
        }
    }

现在编写此代码以显示来自 Array 的图像

/// Display Photo
let asset = allPhotos?.object(at: indexPath.row)
self.imageview.fetchImage(asset: asset!, contentMode: .aspectFit, targetSize: self.imageview.frame.size) 


// Or Display image in Collection View cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "photoCell", for: indexPath) as! SelectPhotoCell

    let asset = allPhotos?.object(at: indexPath.row)
    cell.imgPicture.fetchImage(asset: asset!, contentMode: .aspectFit, targetSize: cell.imgPicture.frame.size)

    return cell
}

extension UIImageView{
 func fetchImage(asset: PHAsset, contentMode: PHImageContentMode, targetSize: CGSize) {
    let options = PHImageRequestOptions()
    options.version = .original
    PHImageManager.default().requestImage(for: asset, targetSize: targetSize, contentMode: contentMode, options: options) { image, _ in
        guard let image = image else { return }
        switch contentMode {
        case .aspectFill:
            self.contentMode = .scaleAspectFill
        case .aspectFit:
            self.contentMode = .scaleAspectFit
        }
        self.image = image
    }
   }
}
于 2018-03-20T12:52:07.967 回答
9

斯威夫特 5 - 更新

首先导入照片

Import Photos

创建一个变量来保存所有图像

var images = [UIImage]()

获取资产并从资产中请求图像的主要功能

fileprivate func getPhotos() {

    let manager = PHImageManager.default()
    let requestOptions = PHImageRequestOptions()
    requestOptions.isSynchronous = false
    requestOptions.deliveryMode = .highQualityFormat
    // .highQualityFormat will return better quality photos
    let fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

    let results: PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
    if results.count > 0 {
        for i in 0..<results.count {
            let asset = results.object(at: i)
            let size = CGSize(width: 700, height: 700)
            manager.requestImage(for: asset, targetSize: size, contentMode: .aspectFill, options: requestOptions) { (image, _) in
                if let image = image {
                    self.images.append(image)
                    self.collectionView.reloadData()
                } else {
                    print("error asset to image")
                }
            }
        }
    } else {
        print("no photos to display")
    }

}
于 2020-01-22T11:32:23.107 回答
1

首先在 info.plist 中检查您的应用是否有权访问库中的照片。比使用以下代码访问所有照片:

PHPhotoLibrary.requestAuthorization { (status) in
        switch status {
        case .authorized:
            print("You Are Authrized To Access")
            let fetchOptions = PHFetchOptions()
            let allPhotos = PHAsset.fetchAssets(with: .image, options: fetchOptions)
            print("Found number of:  \(allPhotos.count) images")
        case .denied, .restricted:
            print("Not allowed")
        case .notDetermined:
            print("Not determined yet")
        }
    }
于 2018-03-20T11:49:48.693 回答