Swift 3 - Fetch All Photos From Library

catcatcat picture catcatcat · Mar 20, 2018 · Viewed 10.7k times · Source

I've tried to fetch photos from the library. It works, but I just got 3 photos from 9 photos from the library. Here's my code:

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!)
            })
        }
    })

When I tried images.count, it said 3. Can anyone help me to find my mistake and get all photos? Big thanks!

Answer

Sapana Ranipa picture Sapana Ranipa · Mar 20, 2018

Try this,

first import photos

import Photos

then declare Array for store photo before viewDidLoad()

var allPhotos : PHFetchResult<PHAsset>? = nil

Now write code for fetch photo in 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")
        }
    }

Now write this code for display image from 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
    }
   }
}