I get the following SwiftUI error:
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
}
I get the following error:
Cannot convert value of type 'UIImage?' to closure result type 'Void'
Instead of computed property, change it to a method with completionHandler
as you are accessing the image asynchronously from the 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)
}
}
Usage
self.assetImage { (image) in
}