将图像从PHAsset加载到Imageview中

时间:2017-05-22 09:39:09

标签: ios swift phasset

我是Swift的新手。在下面的代码中,它检索照片并将它们放在一个数组中。现在我想在图像视图中显示它们。我该怎么办?

我的意思是,例如,如何在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")
    }

另一个问题是:当我调用此函数时,它似乎是异步执行的。我的意思是调用函数后的代码行将提前执行​​。这是因为requestAuthorization?

2 个答案:

答案 0 :(得分:9)

试试这个: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
}

希望它有所帮助。

答案 1 :(得分:1)

你可以这样做: -

创建一个PHAsset类型的空数组: -

fileprivate var imageAssets = [PHAsset]()

通过调用此函数获取所有图像: -

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

    }

请求图片如下: -

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

  })