iOS アプリや macOS アプリに Google ログインを統合する

このページでは、Google ログインを iOS アプリまたは macOS アプリに統合する方法について説明します。この手順は、アプリのライフサイクルや UI モデルに合わせて変更する必要があります。

始める前に

依存関係をダウンロードし、Xcode プロジェクトを構成してクライアント ID を設定します

ログインの仕組みを確認するには、iOS と macOS のサンプルアプリをお試しください

1. 認証リダイレクト URL を処理する

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 で、applicationDidFinishLaunchingkAEGetURL イベントのハンドラを登録します。

    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

アプリのウィンドウまたはシーンで、URL を受け取って GIDSignInhandleURL を呼び出すハンドラを登録します。

Swift

@main
struct MyApp: App {

  var body: some Scene {
    WindowGroup {
      ContentView()
        // ...
        .onOpenURL { url in
          GIDSignIn.sharedInstance.handle(url)
        }
    }
  }
}

2. ユーザーのログイン状態の復元を試みる

アプリの起動時に restorePreviousSignInWithCallback を呼び出して、すでに Google を使用してログインしたユーザーのログイン状態を復元します。これにより、ユーザーは(ログアウトしていない限り)アプリを開くたびにログインする必要がなくなります。

iOS アプリでは多くの場合、macOS アプリの場合、UIApplicationDelegateapplication:didFinishLaunchingWithOptions: メソッドと 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 を使用している場合は、最初のビュー用に restorePreviousSignIn の呼び出しを onAppear に追加します。

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 の [Sign in with 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 ブランディングのボタンを自動的に生成することも(推奨)、カスタム スタイルで独自のボタンを作成することもできます。

    GIDSignInButton をストーリーボードまたは XIB ファイルに追加するには、ビューを追加して、そのカスタムクラスを GIDSignInButton に設定します。ストーリーボードに GIDSignInButton ビューを追加しても、ログインボタンはインターフェース ビルダーでレンダリングされません。アプリを実行してログインボタンを表示します。

    GIDSignInButton の外観は、colorScheme プロパティと style プロパティを設定することでカスタマイズできます。

    GIDSignInButton スタイル プロパティ
    colorScheme kGIDSignInButtonColorSchemeLight
    kGIDSignInButtonColorSchemeDark
    style kGIDSignInButtonStyleStandard
    kGIDSignInButtonStyleWide
    kGIDSignInButtonStyleIconOnly
  2. signIn: を呼び出す ViewController のメソッドにボタンを接続します。たとえば、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. signOut: を呼び出す ViewController のメソッドにボタンを接続します。たとえば、IBAction を使用します。

    Swift

    @IBAction func signOut(sender: Any) {
      GIDSignIn.sharedInstance.signOut()
    }
    

    Objective-C

    - (IBAction)signOut:(id)sender {
      [GIDSignIn.sharedInstance signOut];
    }
    

次のステップ

これで、ユーザーが Google アカウントを使用してアプリにログインできるようになりました。ここでは、次の方法について学びます。