Last active
April 18, 2021 13:56
-
-
Save dmytro-anokhin/51aaeecb03a4e8249d7783cc5c60cb3b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 | |
} | |
} | |
} | |
} |
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
You probably have another
Result
type defined in the module. Try usingSwift.Result
instead.