How to fetch all images from custom Photo Album - Swift

前端 未结 4 811
自闭症患者
自闭症患者 2020-12-03 04:26

How to fetch all images from custom Photo Album?

var fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key:         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 04:39

    SWIFT 4

    func FetchCustomAlbumPhotos()
    {
        let albumName = "AlbumName"
        var assetCollection = PHAssetCollection()
        var albumFound = Bool()
        var photoAssets = PHFetchResult()
    
        let fetchOptions = PHFetchOptions()
        fetchOptions.predicate = NSPredicate(format: "title = %@", albumName)
        let collection:PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
    
        if let _:AnyObject = collection.firstObject{
            //found the album
            assetCollection = collection.firstObject!
            albumFound = true
        }
        else { albumFound = false }
        _ = collection.count
        photoAssets = PHAsset.fetchAssets(in: assetCollection, options: nil) as! PHFetchResult
        let imageManager = PHCachingImageManager()
    
        //        let imageManager = PHImageManager.defaultManager()
    
        photoAssets.enumerateObjects{(object: AnyObject!,
            count: Int,
            stop: UnsafeMutablePointer) in
    
            if object is PHAsset{
                let asset = object as! PHAsset
                print("Inside  If object is PHAsset, This is number 1")
    
                let imageSize = CGSize(width: asset.pixelWidth,
                                       height: asset.pixelHeight)
    
                /* For faster performance, and maybe degraded image */
                let options = PHImageRequestOptions()
                options.deliveryMode = .fastFormat
                options.isSynchronous = true
    
                imageManager.requestImage(for: asset,
                                                  targetSize: imageSize,
                                                  contentMode: .aspectFit ,
                                                  options: options,
                                                  resultHandler: {
                                                    (image, info) -> Void in
                                                    print("Image \(String(describing: image))")
                                                    //self.photo = image!
                                                    /* The image is now available to us */
                                                    //self.addImgToArray(self.photo)
                                                    print("enum for image, This is number 2")
    
                })
    
            }
        }
    }
    

提交回复
热议问题