swift 如何使用token调用Github API?

n9vozmp4  于 2023-06-04  发布在  Swift
关注(0)|答案(1)|浏览(105)

我想使API调用其中列出了所有的追随者的某些用户。我正在测试它,我意识到一个IP可以进行的API调用数量有限。Github文档说如果我使用个人令牌进行API调用,限制数量会增加,但我不知道如何使用令牌进行API调用。

假设我的令牌是bbbb,用户是aaaa,那么我应该如何形成URL?

0dxa2lsx

0dxa2lsx1#

要使用个人令牌对github进行API调用以检索所有your关注者的列表,请尝试这种方法,如示例代码所示(当然要使用有效令牌)。

struct ContentView: View {
    @State var followers: [UserFollower] = []
    
    var body: some View {
        List(followers) { follower in
            Text(follower.login)
        }
        .task {
            await getFollowers()
        }
    }
    
    func getFollowers() async {
        let token = "YOUR-TOKEN"  // <--- here
        if let url = URL(string: "https://api.github.com/user/followers") {
            var request = URLRequest(url: url)
            request.httpMethod = "GET"
            request.setValue("application/vnd.github.v3+json", forHTTPHeaderField: "Accept")
            request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
            request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
            do {
                let (data, _) = try await URLSession.shared.data(for: request)
                followers = try JSONDecoder().decode([UserFollower].self, from: data)
            }
            catch {
                print(error)
            }
        }
    }
    
}

struct UserFollower: Identifiable, Codable {
    let login: String
    let id: Int
    let nodeID: String
    let avatarURL: String
    let gravatarID: String
    let url, htmlURL, followersURL: String
    let followingURL, gistsURL, starredURL: String
    let subscriptionsURL, organizationsURL, reposURL: String
    let eventsURL: String
    let receivedEventsURL: String
    let type: String
    let siteAdmin: Bool
    
    enum CodingKeys: String, CodingKey {
        case login, id, url, type
        case nodeID = "node_id"
        case avatarURL = "avatar_url"
        case gravatarID = "gravatar_id"
        case htmlURL = "html_url"
        case followersURL = "followers_url"
        case followingURL = "following_url"
        case gistsURL = "gists_url"
        case starredURL = "starred_url"
        case subscriptionsURL = "subscriptions_url"
        case organizationsURL = "organizations_url"
        case reposURL = "repos_url"
        case eventsURL = "events_url"
        case receivedEventsURL = "received_events_url"
        case siteAdmin = "site_admin"
    }
}

相关问题