Skip to content

Instantly share code, notes, and snippets.

@dmytro-anokhin
Last active April 18, 2021 13:56
Show Gist options
  • Save dmytro-anokhin/51aaeecb03a4e8249d7783cc5c60cb3b to your computer and use it in GitHub Desktop.
Save dmytro-anokhin/51aaeecb03a4e8249d7783cc5c60cb3b to your computer and use it in GitHub Desktop.
//
// URLImageService+FetchImage.swift
//
// Created by Dmytro Anokhin on 09/01/2021.
//
import Foundation
import Combine
import URLImage
extension URLImageService {
/// Helper function to get an image from the cache or load it from the network.
///
/// Loading starts immediately and the completion closure executed on the main queue. Note: the closure can be exected before the function returns.
/// You must retain the returned object and release it if you want to cancel loading.
func fetchImage(_ url: URL,
options: URLImageOptions? = nil,
completion: @escaping (_ result: Result<ImageInfo, Error>) -> Void) -> Any {
let remoteImage = makeRemoteImage(url: url, options: options)
let cancellable = remoteImage.$loadingState.sink { loadingState in
switch loadingState {
case .initial:
break
case .inProgress:
break
case .success(let transientImage):
completion(.success(transientImage.info))
case .failure(let error):
completion(.failure(error))
}
}
remoteImage.load()
return (remoteImage, cancellable)
}
}
class Example {
private var fetchImageToken: Any?
func fetchImageExample() {
let url = URL(string: "https://homepages.cae.wisc.edu/~ece533/images/lena.png")!
fetchImageToken = URLImageService.shared.fetchImage(url) { result in
switch result {
case .success(let imageInfo):
// Access image via imageInfo.cgImage
break
case .failure(let error):
break
}
}
}
}
@godefroydlb
Copy link

Thanks Dmytro, this will help a lot noobs like me. The thing is it does not compile.
Error messages are :
Result<ImageInfo, Error> -> Cannot specialize non-generic type 'Result'
completion(.success(transientImage.info))-> Type Result has no member success
completion(.failure(error)) -> Type Result has no member failure

@dmytro-anokhin
Copy link
Author

Hey, what Swift version are you using? The Result type was added to the standard library with Swift 5.

@godefroydlb
Copy link

godefroydlb commented Jan 12, 2021 via email

@dmytro-anokhin
Copy link
Author

You probably have another Result type defined in the module. Try using Swift.Result instead.

@godefroydlb
Copy link

You are right. I had a struct named Result and it interfered with your code. Thank for the help. Take care

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment