Search code examples
githubswiftuigithub-api

display Github data using "Github API" (SwiftUI)


task to be done: Make your github data appear on the ContentView screen using the Github API.

struct TaskEntry: Codable  {
    let id: Int
    let title: String
}
    @State var results = [TaskEntry]()
    
    func loadData() {
            guard let url = URL(string: "https://jsonplaceholder.typicode.com/todos") else {
                print("Invalid URL")
                return
            }
            let request = URLRequest(url: url)

            URLSession.shared.dataTask(with: request) { data, response, error in
                if let data = data {
                    if let response = try? JSONDecoder().decode([TaskEntry].self, from: data) {
                        DispatchQueue.main.async {
                            self.results = response
                        }
                        return
                    }
                }
            }.resume()
        }

the above solution did not help in performing this task 👆

i didn't understand how to use these docs

Thank you for attention. help those who know...


Solution

  • try something like this approach to display some info retrieved from github.

    You need to have a model for your info, here I called it Repository. You then need to fetch the info from the github server using the appropriate url as shown in loadData. Finally you need to display the info in your View, as shown in ContentView.

    struct Repository: Decodable, Identifiable {
        let id: Int
        let name, fullName: String
        
        enum CodingKeys: String, CodingKey {
            case id, name
            case fullName = "full_name"
        }
    }
    
    struct ContentView: View {
        @State var results = [Repository]()
        
        var body: some View {
            List {
                ForEach(results) { repo in
                    Text(repo.name)
                }
            }
            .onAppear {
                loadData()
            }
        }
        
        func loadData() {
            guard let url = URL(string: "https://api.github.com/users/workingdog/repos") else { return }
            URLSession.shared.dataTask(with: url) {(data, _, _) in
                guard let data = data else { return }
                    do {
                        self.results = try JSONDecoder().decode([Repository].self, from: data)
                    } catch {
                        print("error: \(error)")
                    }
            }.resume()
        }
    
    }
    

    Note, to retrieve your github repo info, replace workingdog in the url with your github name.

    PS: did you read the answer to your previous question at: get the Field datas according to the Ids from the Collection in the Firestore/SwiftUI

    did the answer not work for you?