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()
}
2
  • One approach is to copy and paste the string you get from print("\(dataString)") into 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. Commented Oct 10, 2022 at 3:35
  • 1
    What is the problem more exactly? Just asking for general help is very vague. Commented Oct 10, 2022 at 6:08

1 Answer 1

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.