使用Firebase Authentication和Google sign In with Swift注册时,将用户数据



当用户第一次在我的iOS应用程序上登录谷歌时,我需要将一些数据存储在Firestore的"用户"集合中。我正在使用Firebase身份验证。要存储的数据是:

  • id:用户的UID
  • 显示名称:用户的全名
  • photoURL:用户的谷歌帐户的url
  • points:当用户第一次登录时,该值将为0
  • knownLanguage代码:当用户第一次登录时,这将是一个空数组

目前,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!) {
}
//...

我正在使用SwiftUI作为UI。

是的,一切都是正确的,但您缺少调用此函数GIDSignIn.sharedInstance((.signIn((

与其使用AppDelegate,不如在UIViewController中对UIButton的作用执行此过程。我认为您缺少GIDSignIn.sharedInstance()?.signIn(),并且在应用程序启动时不应调用此方法,///(例如在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

最新更新