iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐈
Displaying downloaded images in SwiftUI
Code to display an image downloaded from a server in SwiftUI.
func downloadImageAsync(url: URL, completion: @escaping (UIImage?) -> Void) {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, _, _) in
var image: UIImage?
if let imageData = data {
image = UIImage(data: imageData)
}
DispatchQueue.main.async {
completion(image)
}
}
task.resume()
}
How to call it.
ContentView.swift
struct ContentView: View {
@State var image: UIImage?
var body: some View {
VStack {
Text("Hello, world!")
.padding()
if let image = image {
Image(uiImage: image)
}
}
.onAppear {
let url = "https://storage.googleapis.com/zenn-user-upload/avatar/fa39308ce0.jpeg"
downloadImageAsync(url: URL(string: url)!) { image in
self.image = image
}
}
}
}
After writing the article, I found a much easier and smarter way 💦
Discussion
すごいそれっぽい
AsyncImageというのがでるみたいですよ!iOS15からですが。。。
Viewを作るのは考え付かなかった、さすがApple様☺️