iOS 또는 macOS 앱에 Google 로그인 통합

이 페이지에서는 iOS 또는 macOS 앱에 Google 로그인을 통합하는 방법을 보여줍니다. 앱의 수명 주기 또는 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 앱은 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 계정으로 로그인' 버튼을 추가합니다. Google 브랜딩이 적용된 버튼을 자동으로 생성하는 구성요소는 SwiftUI 및 UIKit에서 사용할 수 있으며 사용하는 것이 좋습니다.

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을 만들고 버튼의 이니셜라이저에서 viewModelGoogleSignInButton(viewModel: yourViewModel, action: yourAction)를 사용하여 설정해야 합니다. 자세한 내용은 GoogleSignInButtonViewModel 소스 코드 를 참고하세요.

UIKit 사용

  1. 로그인 뷰에 'Google 계정으로 로그인' 버튼을 추가합니다. GIDSignInButton 클래스를 사용하여 Google 브랜딩이 적용된 버튼을 자동으로 생성하거나 (권장) 커스텀 스타일이 적용된 자체 버튼을 만들 수 있습니다.

    스토리보드 또는 XIB 파일에 GIDSignInButton을 추가하려면 뷰를 추가하고 커스텀 클래스를 GIDSignInButton으로 설정합니다. 스토리보드에 GIDSignInButton 뷰를 추가하면 인터페이스 빌더에서 로그인 버튼이 렌더링되지 않습니다. 로그인 버튼을 보려면 앱을 실행합니다.

    GIDSignInButton의 모양은 colorSchemestyle 속성을 설정하여 맞춤설정할 수 있습니다.

    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 계정을 사용하여 앱에 로그인할 수 있으므로 다음 방법을 알아보세요.