我收到以下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'
答案 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}}