Created
April 4, 2020 11:50
-
-
Save donchan922/f27a81f8946e68044eb124b59398acfb to your computer and use it in GitHub Desktop.
SwiftUIでAPI呼び出しでJSONをパース&画像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 | |
import SDWebImage | |
import SDWebImageSwiftUI | |
struct Dog: Codable, Identifiable { | |
public var id: String | |
public var status: String | |
enum CodingKeys: String, CodingKey { | |
case id = "message" | |
case status = "status" | |
} | |
init() { | |
self.id = "" | |
self.status = "" | |
} | |
} | |
public class DogFetcher: ObservableObject { | |
@Published var dog = Dog() | |
init() { | |
load() | |
} | |
func load() { | |
guard let url = URL(string: "https://dog.ceo/api/breeds/image/random") else { return } | |
URLSession.shared.dataTask(with: url) { (data, response, error) in | |
DispatchQueue.main.async { | |
self.dog = try! JSONDecoder().decode(Dog.self, from: data!) | |
} | |
}.resume() | |
} | |
} | |
struct ContentView: View { | |
@ObservedObject var fetcher = DogFetcher() | |
var body: some View { | |
VStack { | |
AnimatedImage(url: URL(string: fetcher.dog.id)) | |
.resizable() | |
.indicator(SDWebImageActivityIndicator.large) | |
.scaledToFit() | |
Button(action: { | |
self.fetcher.load() | |
}) { | |
Text("Tap!!!") | |
} | |
} | |
} | |
} | |
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
事前準備
「File」 > 「Swift Packages」 > 「Add Package Dependency...」で以下URLを入力する
https://github.com/SDWebImage/SDWebImageSwiftUI.git