I am trying to fetch all the photos (PHAssets) in an album and appending them in an array so I can pass it as completion parameter.
The code is crashing at the line containing arrayOfPHAsset.append(asset)
. Why? What do I need to change in my code to make it work?
This is the code I am using.
func fetchCustomAlbumPhotos( completion : (_ array : [PHAsset]) -> Void)
{
var assetCollection = PHAssetCollection()
var albumFound = Bool()
var photoAssets = PHFetchResult<AnyObject>()
var arrayOfPHAsset : [PHAsset]!
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", CustomAlbum.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
completion([])
}
_ = collection.count
photoAssets = PHAsset.fetchAssets(in: assetCollection, options: nil) as! PHFetchResult<AnyObject>
let imageManager = PHCachingImageManager()
// let imageManager = PHImageManager.defaultManager()
photoAssets.enumerateObjects({(object: AnyObject!,
count: Int,
stop: UnsafeMutablePointer<ObjCBool>) in
if object is PHAsset{
let asset = object as! PHAsset
print(asset)
arrayOfPHAsset.append(asset)
// 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: .aspectFill,
// options: options,
// resultHandler: {
// (image, info) -> Void in
//// self.photo = image!
//// /* The image is now available to us */
//// self.addImgToArray(uploadImage: self.photo)
// print("enum for image, This is number 2")
//
// })
}
})
print("arrayOfPHAsset : \(arrayOfPHAsset), arrayOfPHAsset count : \(arrayOfPHAsset.count)")
completion(arrayOfPHAsset)
}
The following line in the code you are showing is not allocating the array; it is just declaring it.
var arrayOfPHAsset : [PHAsset]!
You need to allocate the array too.
var arrayOfPHAsset : [PHAsset] = []
Then you can add items to the array.
arrayOfPHAsset.append(asset)