Cette page explique comment intégrer Google Sign-In à une application iOS ou macOS. Vous devrez peut-être adapter ces instructions au cycle de vie ou au modèle d'interface utilisateur de votre application.
Avant de commencer
Téléchargez les dépendances, configurez votre projet Xcode et définissez votre ID client.
Essayez notre application exemple iOS et macOS pour voir comment fonctionne Sign-In.
1. Gérer l'URL de redirection de l'authentification
Une fois qu'un utilisateur s'est authentifié auprès de Google, le flux d'authentification est redirigé vers votre application avec une URL contenant la réponse d'authentification, y compris le jeton d'ID de l'utilisateur. Le transfert de cette URL à GIDSignIn permet au SDK d'analyser la réponse et de renvoyer les identifiants de l'utilisateur à votre application.
iOS: UIApplicationDelegate
Dans la méthode application:openURL:options de votre AppDelegate, appelez la méthode handleURL: de GIDSignIn :
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
Dans l'AppDelegate de votre application, enregistrez un gestionnaire pour les événements
kAEGetURLdansapplicationDidFinishLaunching: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]; }Définissez le gestionnaire de ces événements qui appelle
handleURLdeGIDSignIn: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
Dans la fenêtre ou la scène de votre application, enregistrez un gestionnaire pour recevoir l'URL et appelez handleURL de GIDSignIn :
Swift
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
// ...
.onOpenURL { url in
GIDSignIn.sharedInstance.handle(url)
}
}
}
}
2. Tenter de restaurer l'état de connexion de l'utilisateur
Lorsque votre application démarre, appelez restorePreviousSignInWithCallback pour tenter de restaurer l'état de connexion des utilisateurs qui se sont déjà connectés à l'aide de Google. Ainsi, les utilisateurs n'ont pas besoin de se connecter chaque fois qu'ils ouvrent votre application (sauf s'ils se sont déconnectés).
Les applications iOS effectuent souvent cette opération dans la méthode UIApplicationDelegate's
application:didFinishLaunchingWithOptions: et
NSApplicationDelegate's applicationDidFinishLaunching: pour les applications macOS. Utilisez le résultat pour déterminer la vue à présenter à l'utilisateur. Exemple :
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
Si vous utilisez SwiftUI, ajoutez un appel à restorePreviousSignIn dans onAppear pour votre vue initiale :
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. Ajouter un bouton Google Sign-In
Ajoutez un bouton "Se connecter avec Google" à votre vue de connexion. Des composants sont disponibles pour SwiftUI et UIKit, qui génèrent automatiquement un bouton conforme aux consignes de branding Google.
Utiliser SwiftUI
Assurez-vous d'avoir ajouté la dépendance du bouton SwiftUI "Se connecter avec Google" à votre projet.
Dans le fichier où vous souhaitez ajouter le bouton SwiftUI, ajoutez l'importation requise en haut du fichier :
import GoogleSignInSwiftAjoutez une extension
UIApplicationpour récupérer le contrôleur de vue racine actif pour la présentation :extension UIApplication { // Minimal implementation to retrieve the active root view // controller for presentation. Apps presenting sign-in from deeper // within an existing view hierarchy should ensure they select the // appropriate view controller. var rootViewController: UIViewController? { let windowScene = connectedScenes .compactMap { scene in scene as? UIWindowScene } .first { scene in scene.activationState == .foregroundActive } return windowScene?.windows.first(where: { window in window.isKeyWindow })?.rootViewController } }Ajoutez un bouton "Se connecter avec Google" à votre vue et spécifiez l'action qui sera appelée lorsque l'utilisateur appuiera sur le bouton :
GoogleSignInButton(action: handleSignInButton)Déclenchez le processus de connexion lorsque l'utilisateur appuie sur le bouton en ajoutant un appel à la méthode
signIn(withPresenting:completion:)deGIDSignIndans votre action :func handleSignInButton() { guard let rootViewController = UIApplication.shared.rootViewController else { // Handle error return } 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. } }
Cette opération utilise le modèle de vue par défaut qui fournit des informations de style standard pour le bouton. Pour contrôler l'apparence du bouton, vous devez créer un
GoogleSignInButtonViewModel personnalisé et le définir comme viewModel dans l'initialiseur du bouton
à l'aide de GoogleSignInButton(viewModel: yourViewModel, action:
yourAction). Pour en savoir plus, consultez le
GoogleSignInButtonViewModel code source.
Utiliser UIKit
Ajoutez un bouton "Se connecter avec Google" à votre vue de connexion. Vous pouvez utiliser la classe
GIDSignInButtonpour générer automatiquement un bouton avec le branding Google (recommandé) ou créer votre propre bouton avec un style personnalisé.Pour ajouter un
GIDSignInButtonà un storyboard ou à un fichier XIB, ajoutez une vue et définissez sa classe personnalisée surGIDSignInButton. Notez que lorsque vous ajoutez une vueGIDSignInButtonà votre storyboard, le bouton de connexion ne s'affiche pas dans le générateur d'interface. Exécutez l'application pour voir le bouton de connexion.Vous pouvez personnaliser l'apparence d'un
GIDSignInButtonen définissant ses propriétéscolorSchemeetstyle:Propriétés de style GIDSignInButton colorSchemekGIDSignInButtonColorSchemeLight
kGIDSignInButtonColorSchemeDarkstylekGIDSignInButtonStyleStandard
kGIDSignInButtonStyleWide
kGIDSignInButtonStyleIconOnlyConnectez le bouton à une méthode de votre ViewController qui appelle
signIn:. Par exemple, utilisez unIBAction: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. Ajouter un bouton de déconnexion
Ajoutez un bouton de déconnexion à votre application, visible pour les utilisateurs connectés, qui appelle la méthode signOut de GIDSignIn.
L'appel de signOut efface l'état de connexion stocké dans GIDSignIn et supprime les identifiants de l'utilisateur pour votre application du trousseau. Votre application est chargée de mettre à jour son propre état et son interface utilisateur. La déconnexion ne s'applique qu'à votre application. Elle ne déconnecte pas l'utilisateur des autres applications ou services, et ne révoque pas les autorisations que l'utilisateur a accordées à votre application.
Utiliser SwiftUI
Dans SwiftUI, ajoutez un Button qui appelle GIDSignIn.sharedInstance.signOut() :
Button("Sign Out") {
GIDSignIn.sharedInstance.signOut()
// Calling signOut() may not automatically trigger UI updates.
// Update your app's state as needed.
}
Utiliser UIKit
Connectez le bouton à une méthode de votre ViewController qui appelle signOut:. Par exemple, utilisez un IBAction :
Swift
@IBAction func signOut(sender: Any) {
GIDSignIn.sharedInstance.signOut()
}
Objective-C
- (IBAction)signOut:(id)sender {
[GIDSignIn.sharedInstance signOut];
}
Étapes suivantes
Maintenant que les utilisateurs peuvent se connecter à votre application à l'aide de leur compte Google, découvrez comment :
- obtenir les informations de profil du compte Google des utilisateurs.
- s'authentifier auprès de votre backend à l'aide du jeton d'ID Google de l'utilisateur ;
- appeler les API Google au nom de l'utilisateur.