ios - 使用 Google Sign-In with Swift 注册 Firebase 身份验证时将用户数据添加到 Firestore
问题描述
当用户首次在我的 iOS 应用上使用 Google 登录时,我需要将一些数据存储在 Firestore 中的“用户”集合中。我正在使用 Firebase 身份验证。要存储的数据是:
- id:用户的UID
- 显示名称:用户的全名
- photoURL:用户谷歌账号的url
- 积分:当用户首次登录时,这将为 0
- knownLanguageCodes:当用户首次登录时,这将是一个空数组
目前,没有任何内容保存到 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。
解决方案
而不是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
推荐阅读
- visual-studio - 如何制作表格和代码以仅显示每 1 个实体数据的 1 个报告?
- delphi - Delphi android以编程方式显示组合框列表
- c# - 从类中获取 INT 值
- vhdl - vhdl 不能切片记录
- java - 如何从另一个方法访问方法的返回类型
- c3.js - 如何隐藏视图中的列(数字)数据?
- image - React Native 背景图像 - 覆盖和垂直对齐到顶部
- string - Umbraco Razor,比较字符串中的两组页面 ID 是否匹配
- java - JPA 和 1000 ID 在 Oracle IN 运算符中的使用
- command-line - aerender 完成后未退出