在 iOS 或 macOS 應用程式中整合 Google 登入

本頁面說明如何在 iOS 或 macOS 應用程式中整合 Google 登入。您可能需要根據應用程式的生命週期或 UI 模型,調整這些操作說明。

事前準備

下載依附元件、設定 Xcode 專案並設定用戶端 ID

1. 處理驗證重新導向網址

iOS:UIApplication 委派

在 AppCircle 的 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:NSApplication 委派

  1. 在應用程式的 App 委派中,為 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 GoogleSignInSwift
    
  3. 將「使用 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 品牌宣傳功能的按鈕 (建議做法),或使用自訂樣式自行建立按鈕。

    如要在分鏡腳本或 XIB 檔案中加入 GIDSignInButton,請新增檢視畫面,並將自訂類別設為 GIDSignInButton。請注意,將 GIDSignInButton 檢視畫面新增至分鏡腳本時,登入按鈕不會顯示在介面建構工具中。執行應用程式,畫面就會顯示登入按鈕。

    您可以自訂 GIDSignInButton 的外觀,設定其 colorSchemestyle 屬性:

    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 帳戶登入您的應用程式,瞭解如何進行以下操作: