Loading Images from PHAsset to Image

I am new to Swift. In the following code, it retrieves the photos and puts them in an array. Now I want to show them in the images. How can i do this?

I mean, for example, to show an array element in an image view.

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: when I call this function, it seems to execute asynchronously. I mean the lines of code after the function call will be executed earlier. Is it because of requestAuthorization?

+4
source share
2 answers

You can do the following: -

Create an empty array of type PHAsset: -

fileprivate var imageAssets = [PHAsset]()

Retrieve all 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]))
                }  
        }

    }

Image requestShow: -

let availableWidth = UIScreen.main.bounds.size.width
let availableHeight = UIScreen.main.bounds.size.height

imageAssets : -

PHImageManager.default().requestImage(for: imageAssets[0], targetSize: CGSize(width : availableWidth, height : calculatedCellWidth), contentMode: .default, options: nil, resultHandler: { (image, info) in
      requestedImageView.image = image

  })
+1

: 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
}

, .

+4

Source: https://habr.com/ru/post/1677681/


All Articles