Problem: Loading an UIImage with an url obtained from PHAsset returns nil.
Context: I have a UI component which works with image URLs and is populated in different parts of the app with different providers. In a specific case I receive PHAsset.
Code for requesting PHAsset url:
let inputRequestOptions = PHContentEditingInputRequestOptions()
inputRequestOptions.isNetworkAccessAllowed = true
asset.requestContentEditingInput(with: inputRequestOptions, completionHandler: { (edittingInput, _) in
guard let url = edittingInput?.fullSizeImageURL else {
return
}
switch asset.mediaType {
case .image: editMediaContentContainerPresenter.assets = [.image(url)]
case .video: editMediaContentContainerPresenter.assets = [.movie(url)]
default:
debugPrint("unsupported asset")
}
})
Code for loading the URL into an UIImage inside my UI component:
func image(for url: URL, maximumPixelSize: CGFloat) -> UIImage? {
let options = [kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceThumbnailMaxPixelSize: maximumPixelSize] as CFDictionary
guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else {
return nil
}
guard let imageReference = CGImageSourceCreateThumbnailAtIndex(source, 0, options) else {
return nil
}
return UIImage(cgImage: imageReference, scale: UIScreen.main.scale, orientation: .up)
}
Special considerations: I need to transform the PHAsset into an URL because the current UI component is working with many other providers and parts of the app and all of them resolve to URLs. Sometimes the loading from that URL works, but usually maximum once. More often it doesn't manage to load an UIImage from the URL provided.
Question: How can I obtain a valid URL.
Solutions taken into consideration already, but to be avoided:
- loading the image with phasset requests and then saving it separately to a local url
- passing the UIImage instead of URL's