このページでは、Google ログインを iOS アプリまたは macOS アプリと統合する方法について説明します。アプリのライフサイクルまたは UI モデルに合わせて、この手順を変更する必要があります。
始める前に
依存関係をダウンロードし、Xcode プロジェクトを構成してクライアント ID を設定します。
1. 認証リダイレクト URL を処理する
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
アプリのウィンドウまたはシーンで、URL を受け取り、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. } ) }
これは、ボタンの標準スタイル情報を提供するデフォルト ビューモデルを使用しています。ボタンの外観を制御するには、GoogleSignInButton(viewModel: yourViewModel, action:
yourAction)
を使用してカスタムの GoogleSignInButtonViewModel
を作成し、ボタンのイニシャライザで viewModel
として設定する必要があります。詳しくは、GoogleSignInButtonViewModel
ソースコードをご覧ください。
UIKit を使用する
ログイン表示に [Google でログイン] ボタンを追加します。
GIDSignInButton
クラスを使用すると、Google ブランド表示のボタンを自動的に生成したり(推奨)、カスタム スタイルで独自のボタンを作成したりできます。GIDSignInButton
をストーリーボードまたは XIB ファイルに追加するには、ビューを追加して、そのカスタムクラスをGIDSignInButton
に設定します。なお、ストーリーボードにGIDSignInButton
ビューを追加すると、ログインボタンはインターフェース ビルダーでレンダリングされません。アプリを実行してログインボタンを表示する。colorScheme
とstyle
のプロパティを設定することで、GIDSignInButton
の外観をカスタマイズできます。GIDSignInButton スタイル プロパティ colorScheme
kGIDSignInButtonColorSchemeLight
kGIDSignInButtonColorSchemeDark
style
kGIDSignInButtonStyleStandard
kGIDSignInButtonStyleWide
kGIDSignInButtonStyleIconOnly
ボタンを、
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. ログアウト ボタンを追加する
アプリにログアウト ボタンを追加し、ログイン ユーザーに表示します。
ボタンを、
signOut:
を呼び出す ViewController のメソッドに接続します。たとえば、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 を呼び出す。