Swift - 如何获得所有照片的相册包括iCloud Library?

时间:2017-03-24 09:47:13

标签: ios swift

我需要从设备上获取所有相册。我使用此代码来获取相册:

func fetchAlbums() {
       // Get all user albums 
        let userAlbumsOptions = PHFetchOptions()
        userAlbumsOptions.predicate = NSPredicate(format: "estimatedAssetCount > 0")


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

        userAlbums.enumerateObjects( {
            if let collection = $0.0 as? PHAssetCollection {
                print("album title: \(collection.localizedTitle)")

                let onlyImagesOptions = PHFetchOptions()
                onlyImagesOptions.predicate = NSPredicate(format: "mediaType = %i", PHAssetMediaType.image.rawValue)

                if let result = PHAsset.fetchKeyAssets(in: collection, options: onlyImagesOptions) {
                    print("Images count: \(result.count)")
                    if result.count > 0  {
                        //Add album titie
                        self.albumsTitles.append(collection.localizedTitle!)
                        //Add album
                        self.albumsArray.append(result as! PHFetchResult<AnyObject>)
                  }
                }
            }
        } )


    }

但是我无法获得所有照片。所有相册都没有来自iCloud库的照片,只有本地照片。 我使用Collection View来预览照片。我的代码示例用于从所选相册中获取照片:

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: AlbumPhotoCollectionViewCell.self), 
                                  for: indexPath as IndexPath) as! AlbumPhotoCollectionViewCell

                    //Array with albums
                    let asset = self.albumsArray[indexSelectedAlbum]

                    let album = asset[indexPath.item]

                    let options = PHImageRequestOptions()

                    options.isNetworkAccessAllowed = true


               PHImageManager.default().requestImage(for: album as! PHAsset , 
                               targetSize: self.assetThumbnailSize,
                               contentMode: .aspectFill,
                               options: options, 
                               resultHandler: {(result, info)in
                                     if result != nil {

                                       cell.albumPhoto.image = result
                              }
                    })


                    return cell
        }

1 个答案:

答案 0 :(得分:0)

我改变了抓取和所有工作。
旧代码:

if let result = PHAsset.fetchKeyAssets(in: collection, options: onlyImagesOptions){
 //Code
}

新代码

let result = PHAsset.fetchAssets(in: collection, options: onlyImagesOptions)