本页介绍了如何将 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: 方法中执行此操作,而 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向视图添加“使用 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 文件中,可添加一个视图,并将其自定义类设置为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. 添加退出按钮
在应用中添加一个退出按钮,供已登录的用户使用。
将按钮连接到 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。