本页介绍了如何将 Google 登录集成到 iOS 或 macOS 应用中。您可能需要根据应用的生命周期或界面模型调整这些说明。
准备工作
试用我们的 iOS 和 macOS 示例应用,了解登录功能的运作方式。
1. 处理身份验证重定向网址
用户通过 Google 进行身份验证后,身份验证流程会重定向回您的应用,并提供包含身份验证响应(包括用户 ID 令牌)的网址。将此网址传递给 GIDSignIn 可让 SDK 解析响应并将用户的凭据返回给您的应用。
iOS:UIApplicationDelegate
在 AppDelegate 的 application:openURL:options 方法中,调用 GIDSignIn 的 handleURL: 方法:
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
在应用的 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]; }定义这些事件的处理程序,该处理程序会调用
GIDSignIn的handleURL: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
在应用窗口或场景中,注册一个处理程序以接收网址,并调用 GIDSignIn 的 handleURL:
Swift
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
// ...
.onOpenURL { url in
GIDSignIn.sharedInstance.handle(url)
}
}
}
}
2. 尝试恢复用户的登录状态
当应用启动时,调用 restorePreviousSignInWithCallback 尝试恢复已使用 Google 账号登录的用户的登录状态。这样做可确保用户无需在每次打开您的应用时都进行登录(除非他们已退出登录)。
iOS 应用通常在 UIApplicationDelegate 的 application:didFinishLaunchingWithOptions: 方法中执行此操作,而 macOS 应用则在 NSApplicationDelegate 的 applicationDidFinishLaunching: 中执行此操作。使用该结果来确定要向用户呈现哪个视图。例如:
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
确保您已将 SwiftUI“使用 Google 账号登录”按钮的依赖项添加到项目中。
在要添加 SwiftUI 按钮的文件中,将所需的导入添加到文件顶部:
import GoogleSignInSwift添加
UIApplication扩展程序以检索用于演示的有效根视图控制器:extension UIApplication { // Minimal implementation to retrieve the active root view // controller for presentation. Apps presenting sign-in from deeper // within an existing view hierarchy should ensure they select the // appropriate view controller. var rootViewController: UIViewController? { let windowScene = connectedScenes .compactMap { scene in scene as? UIWindowScene } .first { scene in scene.activationState == .foregroundActive } return windowScene?.windows.first(where: { window in window.isKeyWindow })?.rootViewController } }向视图添加“使用 Google 账号登录”按钮,并指定在按下该按钮时将调用的操作:
GoogleSignInButton(action: handleSignInButton)在操作中添加对
GIDSignIn的signIn(withPresenting:completion:)方法的调用,以便在按下按钮时触发登录流程:func handleSignInButton() { guard let rootViewController = UIApplication.shared.rootViewController else { // Handle error return } 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
向登录视图添加“使用 Google 账号登录”按钮。您可以使用
GIDSignInButton类自动生成带有 Google 品牌的按钮(推荐),也可以创建具有自定义样式的按钮。如需将
GIDSignInButton添加到故事板或 XIB 文件中,可添加一个视图,并将其自定义类设置为GIDSignInButton。请注意,当您将一个GIDSignInButton视图添加到故事板时,界面构建器中不会显示登录按钮。运行应用后才能看到登录按钮。您可以通过设置
GIDSignInButton的colorScheme和style属性来自定义其外观:GIDSignInButton 样式属性 colorSchemekGIDSignInButtonColorSchemeLight
kGIDSignInButtonColorSchemeDarkstylekGIDSignInButtonStyleStandard
kGIDSignInButtonStyleWide
kGIDSignInButtonStyleIconOnly将按钮连接到 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. 添加退出按钮
向应用添加一个退出按钮,该按钮对已登录的用户可见,并且会调用 GIDSignIn 的 signOut 方法。
调用 signOut 会清除存储在 GIDSignIn 中的登录状态,并从密钥链中移除用户针对您应用的凭据。您的应用负责更新自己的状态和界面。退出登录仅适用于您的应用。它不会让用户退出其他应用或服务,也不会撤消用户授予您应用的权限。
使用 SwiftUI
在 SwiftUI 中,添加一个调用 GIDSignIn.sharedInstance.signOut() 的 Button:
Button("Sign Out") {
GIDSignIn.sharedInstance.signOut()
// Calling signOut() may not automatically trigger UI updates.
// Update your app's state as needed.
}
使用 UIKit
将按钮连接到 ViewController 中调用 signOut: 的方法。例如,使用 IBAction:
Swift
@IBAction func signOut(sender: Any) {
GIDSignIn.sharedInstance.signOut()
}
Objective-C
- (IBAction)signOut:(id)sender {
[GIDSignIn.sharedInstance signOut];
}
后续步骤
现在,用户可以使用 Google 账号登录您的应用了,接下来请了解如何执行以下操作:
- 获取用户的 Google 账号个人资料信息。
- 使用用户的 Google ID 令牌向后端进行身份验证。
- 代表用户调用 Google API。