SwiftUI错误:无法转换“ UIImage”类型的值?关闭结果类型“无效”

时间:2020-09-23 02:20:39

标签: ios swift swiftui photo phasset

我收到以下SwiftUI错误:

var assetImage : UIImage? {
        if PHPhotoLibrary.authorizationStatus() == .authorized {
            let allPhotosOptions = PHFetchOptions()
            allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
            let assetsFetchResults = PHAsset.fetchAssets(with: allPhotosOptions)
            if assetsFetchResults.count > 0 {
                let asset = assetsFetchResults.lastObject
                if asset != nil {
                    let options = PHImageRequestOptions()
                    options.isNetworkAccessAllowed = true
                    options.version = .current
                    
                    PHCachingImageManager().requestImage(for: asset!, targetSize: CGSize(width: 64 * UIScreen.main.scale, height: 64 * UIScreen.main.scale), contentMode: .aspectFill, options: options, resultHandler: { img, _ in
                        DispatchQueue.main.async {
                            return img //Error Here
                        }
                    })
                } else {
                    return nil
                }
            } else {
                return nil
            }
        }
        return nil
    }

我收到以下错误:

Cannot convert value of type 'UIImage?' to closure result type 'Void'

1 个答案:

答案 0 :(得分:2)

当您从completionHandler异步访问图像时,请使用PHCachingImageManager将其更改为使用func assetImage(_ completion: @escaping (UIImage?) -> Void) { if PHPhotoLibrary.authorizationStatus() == .authorized { let allPhotosOptions = PHFetchOptions() allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)] let assetsFetchResults = PHAsset.fetchAssets(with: allPhotosOptions) if assetsFetchResults.count > 0 { let asset = assetsFetchResults.lastObject if asset != nil { let options = PHImageRequestOptions() options.isNetworkAccessAllowed = true options.version = .current PHCachingImageManager().requestImage(for: asset!, targetSize: CGSize(width: 64 * UIScreen.main.scale, height: 64 * UIScreen.main.scale), contentMode: .aspectFill, options: options, resultHandler: { img, _ in DispatchQueue.main.async { completion(img) } }) } else { completion(nil) } } else { completion(nil) } } else { completion(nil) } } 的方法。

    self.assetImage { (image) in
        
    }

用法

{{1}}