SwiftUI 错误:无法转换“UIImage”类型的值?关闭结果类型“无效”
Posted
技术标签:
【中文标题】SwiftUI 错误:无法转换“UIImage”类型的值?关闭结果类型“无效”【英文标题】:SwiftUI Error : Cannot convert value of type 'UIImage?' to closure result type 'Void' 【发布时间】:2020-09-23 02:20:39 【问题描述】:我收到以下 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】:当您从 PHCachingImageManager
异步访问图像时,将其更改为带有 completionHandler
的方法,而不是计算属性。
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
【讨论】:
如何在 View body 中调用它? var body: some View self.assetImage (image) in Image(uiImage: image!) 似乎不起作用。 @Gizmodo 请查看this 了解如何设置图像。以上是关于SwiftUI 错误:无法转换“UIImage”类型的值?关闭结果类型“无效”的主要内容,如果未能解决你的问题,请参考以下文章
将 SwiftUI 视图渲染到屏幕外并将视图另存为 UIImage 以共享
SwiftUI ImagePicker 保存(图像-> UIImage--> 数据)到核心数据
SwiftUI 错误修复“无法将 'Binding<int>' 类型的值转换为预期类型 'Binding<_>?'”
如何解决此错误:无法将类型“__NSCFString”(0x10354a248)的值转换为“UIImage”(0x104c42b48)