Created
October 12, 2019 18:53
-
-
Save wtsnz/e09be7926115a8ac883c7c72ea5789dc to your computer and use it in GitHub Desktop.
(Extremely) Basic way to load a remote image from URL in SwiftUI
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 Combine | |
import SwiftUI | |
class RemoteImageLoader: ObservableObject { | |
@Published var data: Data = Data() | |
init(imageURL: URL) { | |
URLSession.shared.dataTask(with: imageURL) { data, response, error in | |
guard let data = data else { return } | |
DispatchQueue.main.async { self.data = data } | |
} | |
.resume() | |
} | |
} | |
struct URLImage: View { | |
@ObservedObject var remoteImageLoader: RemoteImageLoader | |
init(_ imageUrl: URL) { | |
remoteImageLoader = RemoteImageLoader(imageURL: imageUrl) | |
} | |
var body: some View { | |
Image(uiImage: UIImage(data: remoteImageLoader.data) ?? UIImage()) | |
.resizable() | |
.renderingMode(.original) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment