首页 > 解决方案 > 使用 Google Sign-In with Swift 注册 Firebase 身份验证时将用户数据添加到 Firestore

问题描述

当用户首次在我的 iOS 应用上使用 Google 登录时,我需要将一些数据存储在 Firestore 中的“用户”集合中。我正在使用 Firebase 身份验证。要存储的数据是:

目前,没有任何内容保存到 Firestore。这是我的应用程序委托中处理登录的部分。

class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        FirebaseApp.configure()
        GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
        GIDSignIn.sharedInstance().delegate = self

        return true
    }

    //Only available on iOS 9 and later
    @available(iOS 9.0, *)
    func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {
        return GIDSignIn.sharedInstance().handle(url)
    }

    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) { 
        if let error = error {
            print(error.localizedDescription)
            return
        }

        guard let authentication = user.authentication else { return }
        let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                 accessToken: authentication.accessToken)

        Auth.auth().signIn(with: credential) { (res, err) in

            if let err = err {
                print(err.localizedDescription)
                return
            }

            //I'm not sure if this block of code is in the right place
            let db = Firestore.firestore()
            db.collection("user").document(String((res?.user.uid)!)).setData([
                "id" : String((res?.user.uid)!),
                "displayName" : (res?.user.displayName)!,
                "photoURL" : (res?.user.photoURL)!
                "points" : 0
                "knownLanguageCodes" : []
            ], merge: true)
        } 
    }

    func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {

    }
    //...

我正在为 UI 使用 SwiftUI。

标签: iosswiftfirebasegoogle-cloud-firestorefirebase-authentication

解决方案


而不是AppDelegate,最好在UIViewController动作上做这个过程UIButton。我认为您丢失了GIDSignIn.sharedInstance()?.signIn(),并且在应用程序启动时不应调用此方法,///(例如 in application:didFinishLaunchingWithOptions:)。因此,您可以尝试以下代码进行UIButton操作

//rest of your code

if GIDSignIn.sharedInstance()?.hasPreviousSignIn() == true {

   //perform Your action if a user already sign in

} else {

  GIDSignIn.sharedInstance()?.signIn()

} 

//rest of your code

推荐阅读