GAppAuth

pod License Twitter

这是一个用于处理与 Google Services 相关的 AppAuth 的即插即用类(iOS & macOS)。

通过 cocoapods 安装

只需将此依赖项添加到您的 Podfile 中

pod GAppAuth

GTMAppAuth 的传递依赖会自动添加。

手动安装

GTMAppAuth 依赖项添加到您的 Podfile (Cocoapods) 中,或者手动将文件复制到您的项目目录。将 GAppAuth.swift 添加到您的项目,并按如下方式设置您的项目以使用 AppAuth 与 Google Services。

iOS

  1. https://console.developers.google.com 设置您的项目(APIs & Services -> Credentials -> Create Credentials -> OAuth Client ID -> iOS),以检索 ClientID 和 iOS scheme URL。
  2. 根据需要启用 Google API。
  3. 将 ClientId 和 RedirectUri 添加到您的 Info.plist 中
<key>GAppAuth</key>
<dict>
    <key>RedirectUri</key>
    <string>com.googleusercontent.apps.YOUR-CLIENT-ID:/oauthredirect</string>
    <key>ClientId</key>
    <string>YOUR-CLIENT-ID.apps.googleusercontent.com</string>
</dict>
  1. 将自定义 URL-Scheme 添加到您的项目
<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>com.googleusercontent.apps.YOUR-CLIENT</string>
    </array>
  </dict>
</array>

macOS

  1. https://console.developers.google.com 设置您的项目(APIs & Services -> Credentials -> Create Credentials -> OAuth Client ID -> Other),以检索 ClientID 和 ClientSecret。
  2. 根据需要启用 Google API。
  3. 将 ClientId、ClientSecret 和 RedirectUri 添加到您的 Info.plist 中
<key>GAppAuth</key>
<dict>
    <key>RedirectUri</key>
    <string>com.googleusercontent.apps.YOUR-CLIENT-ID:/oauthredirect</string>
    <key>ClientId</key>
    <string>YOUR-CLIENT-ID.apps.googleusercontent.com</string>
    <key>ClientSecret</key>
    <string>YOUR-SECRET</string>
</dict>
  1. 将自定义 URL-Scheme 添加到您的项目
<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleTypeRole</key>
    <string>Editor</string>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>com.googleusercontent.apps.YOUR-CLIENT</string>
    </array>
  </dict>
</array>

注意: 确保 Sandboxing 已关闭或已正确配置,否则无法打开浏览器窗口。

通用

  1. 为了授权任何 Google 服务,您需要通过 GAppAuth.shared.appendAuthorizationRealm 将相应的 scope 附加到授权请求中(例如,用于访问 Google Drive 的 kGTLRAuthScopeDrive)。
  2. 从任何 UIViewControllerNSViewController 中,通过调用 GAppAuth.shared.authorize 启动授权工作流程。
  3. 您可能希望在应用程序启动时检索任何现有的授权状态,这可以通过 GAppAuth.shared.retrieveExistingAuthorizationState 来完成。
  4. 您可以通过两个闭包来监视任何更改:stateChangeCallback 或错误 errorCallback

注意: 如果用户撤销了访问权限,这两个回调都会被调用。

在 AppDelegate 的 didFinishLaunchingWithOptions 中进行第 5 和第 7 步是一个不错的选择。

贡献

欢迎创建 issue 或打开 PR。