Created
October 29, 2024 00:00
-
-
Save profh/e183d21b7aeb5a4623b60995bc2b1dc3 to your computer and use it in GitHub Desktop.
Repos_Async
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 | |
import Foundation | |
struct Repositories: Decodable { | |
let repos: [Repository] | |
enum CodingKeys : String, CodingKey { | |
case repos = "items" | |
} | |
} | |
struct Repository: Decodable { | |
let name: String | |
let htmlURL: String | |
enum CodingKeys : String, CodingKey { | |
case name | |
case htmlURL = "html_url" | |
} | |
} | |
// MARK: Our async function to get repos | |
func fetchRepositories() async throws -> [Repository] { | |
let url = URL(string: "https://api.github.com/search/repositories?q=language:swift&sort=stars&order=desc")! | |
let (data, _) = try await URLSession.shared.data(from: url) | |
return try JSONDecoder().decode(Repositories.self, from: data).repos | |
} | |
// MARK: A task to run our async function | |
Task { | |
print("Step 1: Start Task") | |
do { | |
print("Step 2: Call fetchRepositories") | |
let repos = try await fetchRepositories() | |
print("Step 3: Print out key data") | |
for repo in repos { | |
print(" - \(repo.name): \(repo.htmlURL)") | |
} | |
print("Step 4: Finish printing") | |
} catch { | |
print("Hit an error in Step 2: ") | |
print(error) | |
} | |
print("Step 5: Finish task") | |
} | |
print("Step 6: Outside of the task") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment