本页介绍了如何将 Google 登录功能集成到 iOS 或 macOS 应用中。您可能需要针对应用的生命周期或界面模型调整这些说明。
准备工作
试用我们的 iOS 和 macOS 示例应用,了解登录功能的运作方式。
1. 处理身份验证重定向网址
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:
方法和 NSApplicationDelegate
的 applicationDidFinishLaunching:
(对于 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
确保您已将 SwiftUI“使用 Google 账号登录”按钮的依赖项添加到您的项目中。
在要添加 SwiftUI 按钮的文件中,将所需的导入添加到文件顶部:
import GoogleSignInSwift
将“使用 Google 账号登录”按钮添加到您的视图中,并指定按下该按钮时将调用的操作:
GoogleSignInButton(action: handleSignInButton)
通过在您的操作中添加对
GIDSignIn
的signIn(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
在您的登录视图中添加“使用 Google 帐号登录”按钮。您可以使用
GIDSignInButton
类自动生成带有 Google 品牌标记的按钮(推荐),或创建自己的自定义样式按钮。如需将
GIDSignInButton
添加到故事板或 XIB 文件中,请添加一个 View,并将其自定义类设置为GIDSignInButton
。请注意,当您将GIDSignInButton
视图添加到故事板时,界面构建器中不会显示登录按钮。运行应用即可查看登录按钮。您可以通过设置
GIDSignInButton
的colorScheme
和style
属性来自定义其外观:GIDSignInButton 样式属性 colorScheme
kGIDSignInButtonColorSchemeLight
kGIDSignInButtonColorSchemeDark
style
kGIDSignInButtonStyleStandard
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. 添加退出按钮
在您的应用中添加退出按钮,使其对已登录的用户可见。
将该按钮连接到 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。