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

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

事前準備

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

試用我們的 iOS 和 macOS 範例應用程式,瞭解登入功能的運作方式

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

iOS:UIApplicationDelegate

在 AppDelegate 的 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:NSApplicationDelegate

  1. 在應用程式的 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];
    }
    
  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: 方法中執行這項操作,而 macOS 應用程式則會在 NSApplicationDelegateapplicationDidFinishLaunching: 中執行。使用結果判斷要向使用者顯示哪個檢視畫面。例如:

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. 在 View 中新增「使用 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 品牌宣傳的按鈕 (建議),也可以建立自訂樣式的按鈕。

    如要將 GIDSignInButton 加入分鏡腳本或 XIB 檔案,請新增 View,並將自訂類別設為 GIDSignInButton。請注意,將 GIDSignInButton 檢視區塊新增至情節腳本時,登入按鈕不會在介面建構工具中算繪。執行應用程式,查看登入按鈕。

    您可以設定 GIDSignInButtoncolorSchemestyle 屬性,自訂其外觀:

    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 帳戶登入您的應用程式,接下來請瞭解如何: