Firebase使用SwiftUI匿名登录



有人能帮我匿名配置Firebase signIn吗?事实上,我可以匿名登录。然而,每当我启动一个新的模拟器时,我都会得到错误";没有用户登录";。当重新启动这个新模拟器时,错误就会消失,然后我就可以获得userId了。

这是我的初始代码:

import SwiftUI
import Firebase
@main
struct DyeNotesApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

var body: some Scene {
WindowGroup {
ContentView() 
}
}
}
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions laychOptions:
[UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {

FirebaseApp.configure()
if Auth.auth().currentUser == nil {
Auth.auth().signInAnonymously()
}

return true
}
}

这是与Firebase对话的课程:

class MainRepository: ObservableObject {
private let path:String = "MainCollection"
private let db = Firestore.firestore()
@Published var model:[Model] = []

init() {
getData()
}

func getData() {
if let userId = Auth.auth().currentUser?.uid {
db.collection(path)
.order(by: "createdTime", descending: true)
.whereField("userId", isEqualTo: userId)
.addSnapshotListener { (snapshot, error) in
if let snapshot = snapshot {
self.model = snapshot.documents.compactMap{ document in
do {
let x = try document.data(as: Model.self)
return x
}
catch {
print(error)
}
return nil
}
}
}
} else {
print("There is no user logged in")
}
}

我在youtube视频评论中找到了一个解决方案:"。。。通过组合捕获用户id的改变并在用户改变时触发快照监视";。但我不知道如何实现它。

有人能帮我编写这个解决方案的代码吗?如何在用户更改时实现快照以进行监控?

我建议:

  1. 重构代码以移动
if Auth.auth().currentUser == nil {
Auth.auth().signInAnonymously()
}

从应用程序委托到其他地方,为了简单起见,您可以将其放在MainRepository中,但最好将其放其他位置,在可以注入此类的某个身份验证组件中。

  1. 当您调用.signInAnonymously()时,使用完成处理程序调用它
Auth.auth().signInAnonymously { result, error in
}

然后,您可以将结果对象存储在内存中,该内存将包含一个userid,并且您可以在成功登录后cal获取数据。

当前,您的应用程序在签名完成之前正在调用getData。所以它失败了,它在重新启动时工作,因为用户是从上一个会话登录的。

基于Seamus的线索,我创建了signIn((函数,从中开始身份验证。所以我直接在signIn((内部调用getData((。下面是代码。PS:我在MainRepository的init中调用signIn((。

func signIn() {
if Auth.auth().currentUser == nil {
Auth.auth().signInAnonymously { authResult, error in
self.userId = authResult?.user.uid ?? "" // userId was declared as a @Published

self.addFirstView(self.model) // it adds the first collection in the Firestore for a new visiting user, and contains the userId.
self.getData()
}
} 
else {
self.userId = Auth.auth().currentUser?.uid ?? ""
self.getData()
}
}

最新更新