Created
April 3, 2020 13:57
-
-
Save donchan922/571d362ba3ad0650bd5a335de5c3088e to your computer and use it in GitHub Desktop.
SwiftUIで画像URLから画像を表示するサンプルコード
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 | |
class ImageDownloader : ObservableObject { | |
@Published var downloadData: Data? = nil | |
func downloadImage(url: String) { | |
guard let imageURL = URL(string: url) else { return } | |
DispatchQueue.global().async { | |
let data = try? Data(contentsOf: imageURL) | |
DispatchQueue.main.async { | |
self.downloadData = data | |
} | |
} | |
} | |
} | |
struct URLImage: View { | |
let url: String | |
@ObservedObject private var imageDownloader = ImageDownloader() | |
init(url: String) { | |
self.url = url | |
self.imageDownloader.downloadImage(url: self.url) | |
} | |
var body: some View { | |
if let imageData = self.imageDownloader.downloadData { | |
let img = UIImage(data: imageData) | |
return VStack { | |
Image(uiImage: img!).resizable() | |
} | |
} else { | |
return VStack { | |
Image(uiImage: UIImage(systemName: "icloud.and.arrow.down")!).resizable() | |
} | |
} | |
} | |
} | |
struct ContentView: View { | |
var body: some View { | |
VStack { | |
URLImage(url: "https://images.dog.ceo/breeds/dalmatian/cooper1.jpg") | |
.aspectRatio(contentMode: .fit) | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment