如何获取 swift 中的相册标题、图像数?

How to fetch photos album title, image count in swift?

我正在构建类似于 iOS 标准照片应用程序的图库应用程序。 (Swift 4.1)

我想获取启动标准照片应用程序时可以看到的缩略图、标题和图像总数。

照片框架似乎比我想象的要复杂。

很难找到解释原因的方法,以及应该处理什么程序。

你能告诉我这件事吗?

达到您要求的最少步数是:

  // import the framework
  import Photos

  // get the albums list
  let albumList = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: nil)

  // you can access the number of albums with
  albumList.count
  // individual objects with
  let album = albumList.object(at: 0)
  // eg. get the name of the album
  album.localizedTitle

  // get the assets in a collection
  func getAssets(fromCollection collection: PHAssetCollection) -> PHFetchResult<PHAsset> {
    let photosOptions = PHFetchOptions()
    photosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
    photosOptions.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.image.rawValue)

    return PHAsset.fetchAssets(in: collection, options: photosOptions)
  }

  // eg.
  albumList.enumerateObjects { (coll, _, _) in
        let result = self.getAssets(fromCollection: coll)
        print("\(coll.localizedTitle): \(result.count)")
    }

  // Now you can:
  // access the count of assets in the PHFetchResult
  result.count

 // get an asset (eg. in a UITableView)
 let asset = result.object(at: indexPath.row)

 // get the "real" image
 PHCachingImageManager.default().requestImage(for: asset, targetSize: CGSize(width: 200, height: 200), contentMode: .aspectFill, options: nil) { (image, _) in
        // do something with the image
    }

我也建议看看Apple sample code for the Photos framework, is not hard to follow, together with the Photos framework documentation