Created
October 24, 2024 00:37
-
-
Save takoikatakotako/9ab1c41e8f29d836fcf6c5a725b9e781 to your computer and use it in GitHub Desktop.
GithubのAPIを叩き、リポジトリの情報をリストに表示する(async, await)
This file contains hidden or 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 | |
| struct ContentView: View { | |
| @State var repositories: [Repository] = [] | |
| @State var showingErrorAlert = false | |
| let gitHubAPIRepository = GitHubAPIRepository() | |
| var body: some View { | |
| List(repositories) { repository in | |
| VStack(alignment: .leading) { | |
| Text(repository.name) | |
| .font(Font.system(size: 24).bold()) | |
| Text(repository.description ?? "") | |
| Text("Star: \(repository.stargazersCount)") | |
| } | |
| }.onAppear { | |
| fetchRepositories() | |
| } | |
| .alert("Error", isPresented: $showingErrorAlert) { | |
| Button("Close", action: {}) | |
| } message: { | |
| Text("Failed to Fetch repositories.") | |
| } | |
| } | |
| @MainActor | |
| func fetchRepositories() { | |
| Task { | |
| do { | |
| repositories = try await gitHubAPIRepository.searchRepos(page: 1, perPage: 20) | |
| } catch { | |
| showingErrorAlert = true | |
| } | |
| } | |
| } | |
| } | |
| #Preview { | |
| ContentView() | |
| } |
This file contains hidden or 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 Foundation | |
| struct GitHubAPIRepository { | |
| func searchRepos(page: Int, perPage: Int) async throws -> [Repository] { | |
| let url = URL(string: "https://api.github.com/search/repositories?q=swift&sort=stars&page=\(page)&per_page=\(perPage)")! | |
| let (data, _) = try await URLSession.shared.data(from: url) | |
| let response = try JSONDecoder().decode(GithubSearchResult.self, from: data) | |
| return response.items | |
| } | |
| } | |
| struct GithubSearchResult: Codable { | |
| let items: [Repository] | |
| } | |
| struct Repository: Codable, Identifiable, Equatable { | |
| let id: Int | |
| let name: String | |
| let description: String? | |
| let stargazersCount: Int | |
| enum CodingKeys: String, CodingKey { | |
| case id | |
| case name | |
| case description | |
| case stargazersCount = "stargazers_count" | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment