【问题标题】:Calling Google Sheets API in Swift with GTMAppAuth使用 GTMAppAuth 在 Swift 中调用 Google Sheets API
【发布时间】:2020-06-23 13:59:58
【问题描述】:

我正在尝试在 macOS 上使用 Swift 读取/写入 Google 表格。 我正在使用 GAppAuth 库,该库又使用 GTMAppAuth

我设法获得了授权并取回了访问令牌和刷新令牌,但是当我尝试调用 Google 表格的一个端点时,我仍然收到 403 的 HTTP 状态代码。

applicationDidFinishLaunching(_:)中我附加了以下授权范围,详见documentation

GAppAuth.shared.appendAuthorizationRealm("https://www.googleapis.com/auth/spreadsheets.readonly")

但是,我仍然得到 403。我做错了什么?我是否正确添加了范围?

这是我进行 API 调用的代码:

@IBAction func getSpreadsheet(_ sender: NSButton) {
    
    let fetcherService = GTMSessionFetcherService()
    fetcherService.authorizer = authorization
    let spreadsheetInfo = URL(string: "https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetID}")
    let fetcher = GTMSessionFetcher(url: spreadsheetInfoEndpoint)
    fetcher.beginFetch { (data, error) in
        //Error code 403
    }
}

【问题讨论】:

  • 你好@nasonov!我看到您使用的是第三方 GAppAuth 库而不是官方的 Google Auth 存储库。为了更好地确定问题的根源,您能否使用 Google Auth 请求一个有效的令牌并将其用于 Sheets API 请求?
  • 谢谢雅克,我一定会去看看。在查看doc 时,我停在了底部链接的资源处。我没有想到 Google API 存储库中会有其他人。

标签: swift macos oauth-2.0 google-sheets-api google-oauth


【解决方案1】:

我通过使用 Google API Explorer 查看 cURL 请求使其正常工作。缺少访问令牌参数:

https://sheets.googleapis.com/v4/spreadsheets/[SPREADSHEETID]/values/[RANGE]?access_token=[access_token]

还要感谢评论区的 Jacques-Guzel Heron,他让我知道了官方 Google Auth Library for Swift。我去看看。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多