4

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?

A.bee
  • 502
  • 5
  • 16

2 Answers2

17

Try this: imageView.image = convertImageFromAsset(list[0])

func convertImageFromAsset(asset: PHAsset) -> UIImage {
    let manager = PHImageManager.default()
    let option = PHImageRequestOptions()
    var image = UIImage()
    option.isSynchronous = true
    manager.requestImage(for: asset, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFit, options: option, resultHandler: {(result, info)->Void in
        image = result!
    })
    return image
}

Hope it helps.

Ashik
  • 1,204
  • 12
  • 22
2

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

  })
Himanshu
  • 2,832
  • 4
  • 23
  • 51
  • When I call this function and want to set the image in the imageview, it raises: fatal error: Index out of range. It Asynchronous execution is still remains. – A.bee May 22 '17 at 11:21
  • Do you have any image in your device? – Himanshu May 22 '17 at 12:27
  • Yes. I solved it by placing the last line code into authorized closure and it works. But I want do it in a synchronous way. – A.bee May 22 '17 at 13:01