[swift] Swift와 Firebase를 이용한 소셜 로그인 기능 구현하기

이번에는 Swift 언어와 Firebase를 사용하여 소셜 로그인 기능을 구현하는 방법에 대해 알아보겠습니다. 소셜 로그인은 사용자가 소셜 미디어 계정을 사용하여 앱에 로그인할 수 있는 기능을 말합니다. 이 기능은 매우 편리하고 일반적으로 사용자 인증을 구현하는 데 널리 사용됩니다.

Firebase 프로젝트 설정

먼저 Firebase 콘솔에서 새로운 프로젝트를 생성하고, iOS 앱을 추가해야 합니다. Firebase 콘솔에서 제공하는 세부 가이드에 따라서 앱을 설정하고 구성 파일(.plist)을 다운로드해야 합니다.

Cocoapods를 사용하여 Firebase 라이브러리 추가하기

프로젝트의 Podfile 파일에 다음 코드를 추가하여 Firebase 라이브러리를 가져옵니다:

pod 'Firebase/Auth'

그리고 터미널에서 pod install 명령을 실행하여 CocoaPods를 통해 Firebase를 설치해야 합니다.

소셜 로그인 구현하기

Firebase는 여러 소셜 로그인 제공업체들과 통합되어 있으므로, 앱에서 원하는 소셜 로그인 제공업체를 선택하여 구현할 수 있습니다. 여기서는 구글 로그인을 예시로 들어보겠습니다.

  1. AppDelegate.swift 파일을 열고, import Firebase 문을 추가합니다.
  2. application(_:didFinishLaunchingWithOptions:) 메서드에 FirebaseApp.configure()를 추가하여 Firebase를 초기화합니다.
import Firebase

// ...

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Firebase 초기화
    FirebaseApp.configure()
    
    // ...
    
    return true
}
  1. Info.plist 파일을 열고, 다음 <key><string>을 추가하여 Google 로그인을 설정합니다. <string>에는 Firebase 콘솔에서 발급받은 클라이언트 ID를 넣어야 합니다.
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>CFBundleURLName</key>
        <string>com.googleusercontent.apps.YOUR_CLIENT_ID</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>com.googleusercontent.apps.YOUR_CLIENT_ID</string>
        </array>
    </dict>
</array>
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>google</string>
</array>
  1. 로그인 버튼을 생성하고, 해당 버튼의 액션 메서드 내에서 다음 코드를 사용하여 소셜 로그인을 처리합니다.
import Firebase
import GoogleSignIn

// ...

@IBAction func signInWithGoogleButtonTapped(_ sender: UIButton) {
    guard let clientID = FirebaseApp.app()?.options.clientID else { return }

    let config = GIDConfiguration(clientID: clientID)
    GIDSignIn.sharedInstance.signIn(with: config, presenting: self) { [weak self] user, error in
        guard let self = self else { return }

        if let error = error {
            print("Google Sign-In Error: \(error.localizedDescription)")
            return
        }

        guard let authentication = user?.authentication, let idToken = authentication.idToken else {
            print("Google Sign-In Error: Failed to get authentication information")
            return
        }

        let credential = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: nil)

        Auth.auth().signIn(with: credential) { _, error in
            if let error = error {
                print("Firebase Sign-In Error: \(error.localizedDescription)")
            } else {
                print("Firebase Sign-In Successful!")
                // 로그인에 성공한 경우 원하는 동작을 수행합니다.
            }
        }
    }
}

이렇게 구현하면 사용자가 구글 계정으로 로그인을 시도하면 Firebase를 통해 인증을 처리하고 앱에 로그인할 수 있습니다.

이제는 다른 소셜 로그인 제공업체들에 대해서도 마찬가지로 구현할 수 있습니다. Firebase 공식 문서에서 제공하는 가이드를 참조하면 다양한 소셜 로그인 기능을 구현하는 방법을 자세히 알 수 있습니다.

결론

이번 글에서는 Swift와 Firebase를 이용하여 소셜 로그인 기능을 구현하는 방법에 대해 알아보았습니다. Firebase의 소셜 로그인 통합을 통해 사용자 인증을 간편하게 구현할 수 있으며, 다른 소셜 미디어 제공업체들과의 통합도 가능합니다. Firebase와 Swift를 사용하여 소셜 로그인 기능을 구현하는 개발자들에게 도움이 되었기를 바랍니다.