I'm new in Swift. In the following code, it retrieve photos and put them in an array. Now I want to show them in imageviews. How can I do it?
I mean how ,for example, show an element of the array in an imageview.
var list :[PHAsset] = []
PHPhotoLibrary.requestAuthorization { (status) in
switch status
{
case .authorized:
print("Good to proceed")
let fetchOptions = PHFetchOptions()
let allPhotos = PHAsset.fetchAssets(with: .image, options: fetchOptions)
print(allPhotos.count)
allPhotos.enumerateObjects({ (object, count, stop) in
list.append(object)
})
print("Found \(allPhotos.count) images")
case .denied, .restricted:
print("Not allowed")
case .notDetermined:
print("Not determined yet")
}
Another question is: When I call this function it seems it execute Asynchronously. I mean code lines after calling the function will be executed early. Is this because of requestAuthorization?
You can do like this :-
Create an empty array of type PHAsset :-
fileprivate var imageAssets = [PHAsset]()
Fetch all the images by calling this function :-
func fetchGallaryResources(){
let status = PHPhotoLibrary.authorizationStatus()
if (status == .denied || status == .restricted) {
self.showAlert(cancelTitle: nil, buttonTitles:["OK"], title: "Oops", message:"Access to PHPhoto library is denied.")
return
}else{
PHPhotoLibrary.requestAuthorization { (authStatus) in
if authStatus == .authorized{
let imageAsset = PHAsset.fetchAssets(with: .image, options: nil)
for index in 0..<imageAsset.count{
self.imageAssets.append((imageAsset[index]))
}
}
}
Request for the imageLike this :-
let availableWidth = UIScreen.main.bounds.size.width
let availableHeight = UIScreen.main.bounds.size.height
Take out the image from imageAssets in a loop or single one just like that :-
PHImageManager.default().requestImage(for: imageAssets[0], targetSize: CGSize(width : availableWidth, height : calculatedCellWidth), contentMode: .default, options: nil, resultHandler: { (image, info) in
requestedImageView.image = image
})