将 Google 登录功能集成到您的 iOS 或 macOS 应用中

本页介绍了如何将 Google 登录功能集成到 iOS 或 macOS 应用中。您可能需要针对应用的生命周期或界面模型调整这些说明。

准备工作

下载依赖项,配置您的 Xcode 项目并设置您的客户端 ID

1. 处理身份验证重定向网址

iOS:UIApplicationDelegate

在 AppDelegate 的 application:openURL:options 方法中,调用 GIDSignInhandleURL: 方法:

Swift

func application(
  _ app: UIApplication,
  open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]
) -> Bool {
  var handled: Bool

  handled = GIDSignIn.sharedInstance.handle(url)
  if handled {
    return true
  }

  // Handle other custom URL types.

  // If not handled by this app, return false.
  return false
}

Objective-C

- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
  BOOL handled;

  handled = [GIDSignIn.sharedInstance handleURL:url];
  if (handled) {
    return YES;
  }

  // Handle other custom URL types.

  // If not handled by this app, return NO.
  return NO;
}

macOS:NSApplicationDelegate

  1. 在应用的 AppDelegate 中为 applicationDidFinishLaunching 中的 kAEGetURL 事件注册处理程序:

    Swift

    func applicationDidFinishLaunching(_ notification: Notification) {
      // Register for GetURL events.
      let appleEventManager = NSAppleEventManager.shared()
      appleEventManager.setEventHandler(
        self,
        andSelector: "handleGetURLEvent:replyEvent:",
        forEventClass: AEEventClass(kInternetEventClass),
        andEventID: AEEventID(kAEGetURL)
      )
    }
    

    Objective-C

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
      // Register for GetURL events.
      NSAppleEventManager *appleEventManager = [NSAppleEventManager sharedAppleEventManager];
      [appleEventManager setEventHandler:self
                         andSelector:@selector(handleGetURLEvent:withReplyEvent:)
                         forEventClass:kInternetEventClass
                         andEventID:kAEGetURL];
    }
    
  2. 为调用 GIDSignInhandleURL 的事件定义处理程序:

    Swift

    func handleGetURLEvent(event: NSAppleEventDescriptor?, replyEvent: NSAppleEventDescriptor?) {
        if let urlString =
          event?.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue{
            let url = NSURL(string: urlString)
            GIDSignIn.sharedInstance.handle(url)
        }
    }
    

    Objective-C

    - (void)handleGetURLEvent:(NSAppleEventDescriptor *)event
               withReplyEvent:(NSAppleEventDescriptor *)replyEvent {
          NSString *URLString = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
          NSURL *URL = [NSURL URLWithString:URLString];
          [GIDSignIn.sharedInstance handleURL:url];
    }
    

SwiftUI

在应用的窗口或场景中,注册一个处理程序来接收该网址并调用 GIDSignInhandleURL

Swift

@main
struct MyApp: App {

  var body: some Scene {
    WindowGroup {
      ContentView()
        // ...
        .onOpenURL { url in
          GIDSignIn.sharedInstance.handle(url)
        }
    }
  }
}

2. 尝试恢复用户的登录状态

当应用启动时,调用 restorePreviousSignInWithCallback 来尝试恢复已使用 Google 登录的用户的登录状态。这样做可以确保用户无需在每次打开您的应用时都进行登录(除非用户已退出帐号)。

iOS 应用通常在 UIApplicationDelegateapplication:didFinishLaunchingWithOptions: 方法和 NSApplicationDelegateapplicationDidFinishLaunching:(对于 macOS 应用)中执行此操作。使用结果确定要向用户显示哪个视图。例如:

Swift

func application(
  _ application: UIApplication,
  didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
  GIDSignIn.sharedInstance.restorePreviousSignIn { user, error in
    if error != nil || user == nil {
      // Show the app's signed-out state.
    } else {
      // Show the app's signed-in state.
    }
  }
  return true
}

Objective-C

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GIDSignIn.sharedInstance restorePreviousSignInWithCompletion:^(GIDGoogleUser * _Nullable user,
                                                                  NSError * _Nullable error) {
    if (error) {
      // Show the app's signed-out state.
    } else {
      // Show the app's signed-in state.
    }
  }];
  return YES;
}

SwiftUI

如果您使用的是 SwiftUI,请在 onAppear 中为初始视图添加对 restorePreviousSignIn 的调用:

Swift

@main
struct MyApp: App {
  var body: some Scene {
    WindowGroup {
      ContentView()
        // ...
        .onAppear {
          GIDSignIn.sharedInstance.restorePreviousSignIn { user, error in
            // Check if `user` exists; otherwise, do something with `error`
          }
        }
    }
  }
}

3. 添加 Google 登录按钮

在您的登录视图中添加“使用 Google 帐号登录”按钮。 组件适用于 SwiftUI 和 UIKit,这些组件可自动生成带有 Google 品牌信息的按钮,因此建议使用。

使用 SwiftUI

  1. 确保您已在项目中添加 SwiftUI“使用 Google 帐号登录”按钮的依赖项

  2. 在您要添加 SwiftUI 按钮的文件中,将所需的 import 添加到文件顶部:

    import GoogleSignInSwift
    
  3. 向您的 View 中添加“Sign in with Google”按钮,并指定在按下该按钮时调用的操作:

    GoogleSignInButton(action: handleSignInButton)
    
  4. 通过在您的操作中添加对 GIDSignInsignIn(presentingViewController:completion:) 方法的调用,在按下按钮时触发登录流程:

    func handleSignInButton() {
      GIDSignIn.sharedInstance.signIn(
        withPresenting: rootViewController) { signInResult, error in
          guard let result = signInResult else {
            // Inspect error
            return
          }
          // If sign in succeeded, display the app's main content View.
        }
      )
    }
    

这将使用默认视图模型,该模型提供按钮的标准样式信息。如需控制按钮的外观,您需要创建自定义 GoogleSignInButtonViewModel,并使用 GoogleSignInButton(viewModel: yourViewModel, action: yourAction) 在按钮的初始化程序中将其设置为 viewModel。如需了解详情,请参阅 GoogleSignInButtonViewModel 源代码

使用 UIKit

  1. 在您的登录视图中添加“使用 Google 帐号登录”按钮。您可以使用 GIDSignInButton 类自动生成带有 Google 品牌标识的按钮(推荐),也可以自行创建具有自定义样式的按钮。

    如需将 GIDSignInButton 添加到故事板或 XIB 文件中,请添加一个 View 并将其自定义类设置为 GIDSignInButton。请注意,当您将 GIDSignInButton 视图添加到故事板时,界面构建器中不会显示登录按钮。运行应用以查看登录按钮。

    您可以通过设置 GIDSignInButtoncolorSchemestyle 属性来自定义其外观:

    GIDSignInButton 样式属性
    colorScheme kGIDSignInButtonColorSchemeLight
    kGIDSignInButtonColorSchemeDark
    style kGIDSignInButtonStyleStandard
    kGIDSignInButtonStyleWide
    kGIDSignInButtonStyleIconOnly
  2. 将该按钮关联到 ViewController 中调用 signIn: 的方法。例如,使用 IBAction

    Swift

    @IBAction func signIn(sender: Any) {
      GIDSignIn.sharedInstance.signIn(withPresenting: self) { signInResult, error in
        guard error == nil else { return }
    
        // If sign in succeeded, display the app's main content View.
      }
    }
    

    Objective-C

    - (IBAction)signIn:(id)sender {
      [GIDSignIn.sharedInstance
          signInWithPresentingViewController:self
                                  completion:^(GIDSignInResult * _Nullable signInResult,
                                               NSError * _Nullable error) {
        if (error) {
          return;
        }
    
        // If sign in succeeded, display the app's main content View.
      }];
    }
    

4. 添加退出按钮

  1. 向您的应用添加退出按钮(已登录用户可以看到)。

  2. 将该按钮关联到 ViewController 中调用 signOut: 的方法。例如,使用 IBAction

    Swift

    @IBAction func signOut(sender: Any) {
      GIDSignIn.sharedInstance.signOut()
    }
    

    Objective-C

    - (IBAction)signOut:(id)sender {
      [GIDSignIn.sharedInstance signOut];
    }
    

后续步骤

现在,用户可以使用自己的 Google 帐号登录您的应用,接下来将了解如何执行以下操作: