Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load Images From PHAsset into an Imageview

Tags:

ios

swift

phasset

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?

like image 885
A.bee Avatar asked Dec 02 '22 11:12

A.bee


1 Answers

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.

like image 94
Ashik Avatar answered Dec 05 '22 09:12

Ashik