Reputation: 51
Is there a way of converting array of Phasset to UIImage?
var images = [PHAsset]()
func getImages() {
let assets = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: nil)
assets.enumerateObjects({ (object, count, stop) in
// self.cameraAssets.add(object)
self.images.append(object)
})
//In order to get latest image first, we just reverse the array
self.images.reverse()
Upvotes: 4
Views: 5848
Reputation: 190
let imageManager = PHImageManager.default()
let requestOptions = PHImageRequestOptions()
let fetchOptions = PHFetchOptions()
var imageArray = [UIImage]()
override func viewDidLoad(){
super.viewDidLoad()
requestOptions.isSynchronous = true
requestOptions.deliveryMode =
PHImageRequestOptionsDeliveryMode.highQualityFormat
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
grabphoto()
}
Here, we call grab photo function which fetch PHAsset of type image and also converts it to UIImage
func grabPhotos(){
if let fetchResult : PHFetchResult = PHAsset.fetchAssets(with:.image,options: fetchOptions){
if fetchResult.count > 0{
if let fetchResult : PHFetchResult = PHAsset.fetchAssets(with:.image, options: self.fetchOptions){
self.imageManager.requestImage(for: fetchResult.object(at: indexPath.row) as! PHAsset, targetSize: CGSize(width : 112, height : 116), contentMode: .aspectFill , options:
self.requestOptions, resultHandler: { (image, error) in
self.imageArray.append(image!)})
}
}else {
print("no photos! ")
}
}
}
Upvotes: 0
Reputation: 9734
Convert array of PHASSET
to UIIMAGE
in Swift 4
//MARK: Convert array of PHAsset to UIImages
func getAssetThumbnail(assets: [PHAsset]) -> [UIImage] {
var arrayOfImages = [UIImage]()
for asset in assets {
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
var image = UIImage()
option.isSynchronous = true
manager.requestImage(for: asset, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFit, options: option, resultHandler: {(result, info)->Void in
image = result!
arrayOfImages.append(image)
})
}
return arrayOfImages
}
Upvotes: 6
Reputation: 8506
fileprivate let imageManager = PHCachingImageManager()
// Request an image for the asset from the **PHCachingImageManager**.
let asset = images.object(at: 0) //Index will be dynamic according to your requirement
imageManager.requestImage(for: asset, targetSize: thumbnailSize, contentMode: .aspectFill, options: nil, resultHandler: { image, _ in
print("need image is \(image)")
})
Upvotes: 0