本頁面說明如何將 Google 登入功能整合至 iOS 或 macOS 應用程式。 您可能必須根據應用程式生命週期或 UI 模型調整這些操作說明。
事前準備
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。