Last active
August 19, 2020 15:32
-
-
Save alexito4/59436b9ab0489b00fb137a8382f38ea5 to your computer and use it in GitHub Desktop.
Rough sketch of SwiftUI RemoteImage using AlamofireImage
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
import SwiftUI | |
import Combine | |
import AlamofireImage | |
let imageDownloader = ImageDownloader( | |
configuration: ImageDownloader.defaultURLSessionConfiguration(), | |
downloadPrioritization: .fifo, | |
maximumActiveDownloads: 4, | |
imageCache: AutoPurgingImageCache() | |
) | |
extension ImageDownloader { | |
func image(for url: URL) -> AnyPublisher<UIImage?, Never> { | |
return Publishers.Future { subscriber in | |
let urlRequest = URLRequest(url: url) | |
imageDownloader.download(urlRequest) { response in | |
if let image = response.result.value { | |
subscriber(.success(image)) | |
} | |
} | |
} | |
.eraseToAnyPublisher() | |
} | |
} | |
struct RemoteImage: View { | |
// let placeholder = UIImage(named: "placeholder.jpg")! | |
let url: URL | |
init(url: URL) { | |
print("RemoteImage created \(url)") | |
self.url = url | |
} | |
@State private var image: UIImage? = nil | |
var body: some View { | |
Group { | |
if image != nil { | |
Image(uiImage: image!) | |
} else { | |
Image(systemName: "person.crop.circle") | |
} | |
} | |
.bind(imageDownloader.image(for: url), to: $image) | |
} | |
} | |
//#if DEBUG | |
//struct RemoteImage_Previews : PreviewProvider { | |
// static var previews: some View { | |
// RemoteImage() | |
// } | |
//} | |
//#endif |
bind
is a convenience extension that I've created. The complete implementation can be found here
extension View {
func bind<P: Publisher, Value>(
_ publisher: P,
to state: Binding<Value>
) -> SubscriptionView<P, Self> where P.Failure == Never, P.Output == Value {
return onReceive(publisher) { value in
state.value = value
}
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
fails to build on this line
error