0

I am making an api call to the github api to get the names of folders in a repository. I do not know how to extract the data from the api call and where to go from here. Any help would be appriciated!

Code:

func extractData() {
    let url = URL(string: "https://api.github.com/repos/myrepository/myrepository/contents/folder")!
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        if let error = error {
            print("Error with fetching repos: \(error)")
            return
        }

        guard let httpResponse = response as? HTTPURLResponse,
            (200...299).contains(httpResponse.statusCode) else {
                print("Error with the response, unexpected status code: \(String(describing: response))")
                return
        }

        if let mimeType = httpResponse.mimeType, mimeType == "application/json",
            let data = data,
            let dataString = String(data: data, encoding: .utf8) {
            print("Got data: \(dataString)")
            
            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                    print(json["name"])
                }
            } catch let error as NSError {
                print("Failed to load: \(error.localizedDescription)")
            }

        }
    }
    task.resume()
}
  • One approach is to copy and paste the string you get from `print("\(dataString)")` into https://app.quicktype.io/. This will create the struct models you need to decode the github data. Then use something like: `let response = try JSONDecoder().decode(GithubResponse.self, from: data)` to decode the github response into your models. – workingdog support Ukraine Oct 10 '22 at 03:35
  • 1
    What is the problem more exactly? Just asking for general help is very vague. – Joakim Danielson Oct 10 '22 at 06:08

1 Answers1

1

To get the names of the folders in a repository, try this example code. It shows how to call github and return the list of folders for one of my repo. It then displays the folders in a List.

struct ContentView: View {
    @State var folders: [RepoContent] = []
    
    var body: some View {
        List(folders) { folder in
            Text(folder.name) + Text(" \(folder.type)").foregroundColor(folder.type == "dir" ? .blue : .red)
        }
        .onAppear {
            getRepoFolders(owner: "workingDog", repo: "OWOneCall")
        }
    }

    func getRepoFolders(owner: String, repo: String) {
        
        guard let url = URL(string: "https://api.github.com/repos/\(owner)/\(repo)/contents") else {
            return
        }
        
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            if let error = error {
                print("Error with fetching repos: \(error)")
                return
            }
            
            guard let httpResponse = response as? HTTPURLResponse,
                  (200...299).contains(httpResponse.statusCode) else {
                print("Error with the response, unexpected status code: \(String(describing: response))")
                return
            }
            
            if let data = data {
                do {
                    let response = try JSONDecoder().decode([RepoContent].self, from: data)
                    self.folders = response
                } catch {
                    print("\n error: \(error)\n")
                }
            }
        }
        task.resume()
    }
    
}

// MARK: - RepoContent
struct RepoContent: Identifiable, Codable {
    let id = UUID()
    let name, path, sha: String
    let size: Int
    let url, htmlURL: String
    let gitURL: String
    let downloadURL: String?
    let type: String
    let links: Links

    enum CodingKeys: String, CodingKey {
        case name, path, sha, size, url, type
        case htmlURL = "html_url"
        case gitURL = "git_url"
        case downloadURL = "download_url"
        case links = "_links"
    }
}

// MARK: - Links
struct Links: Codable {
    let linksSelf: String
    let git: String
    let html: String

    enum CodingKeys: String, CodingKey {
        case linksSelf = "self"
        case git, html
    }
}