1

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?

  • Look up Photos Framework. – Lumialxk May 15 '18 at 10:21
  • Possible duplicate of [How can i access the photo from gallery using Photo framework in objective c](https://stackoverflow.com/questions/33144930/how-can-i-access-the-photo-from-gallery-using-photo-framework-in-objective-c) – TheTiger May 15 '18 at 11:36
  • @TheTiger No, I note that in swift –  May 16 '18 at 00:55
  • @allanWay I agreed the question is for `Swift`. But there is no change in approach and methods of Photos Framework for your requirement and the code is easily convertible into `Swift`. Even you can use [online tool](https://objectivec2swift.com/) for converting the code and then ask question for that particular problem which you face in this process. You have asked question for whole functionality instead of specific problem. This is good for a newbie to try first yourself. I hope you understand what I mean. – TheTiger May 16 '18 at 04:32

1 Answers1

7

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.

GreyHands
  • 1,734
  • 1
  • 18
  • 30