iosphotos

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


I'm building Gallery app like a iOS standard Photos App. (Swift 4.1)

I want to fetch the thumbnails, titles, and total number of images that I can see when I launch the standard photo app.

The Photos framework seems more complex than I thought.

It is not easy to find a way to explain why, and what procedures should be approached.

Can you tell me about this?


Solution

  • The minimum number of steps to achieve what you are asking is:

      // 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
        }
    

    I also suggest to take a look at the Apple sample code for the Photos framework, is not hard to follow, together with the Photos framework documentation.