嗨,有人可以帮助我吗?我真的很难让这些初始化工作。由于任务我总是被 xcode 大喊大叫,所以并不是所有的属性都被初始化了:
`
进口粉底 导入 FirebaseFirestore
ChatViewModel 类:ObservableObject {
@Published var chat: ChatModel
@Published var opposingUser: User
init(oppUser: User) {
self.opposingUser = oppUser
Task {
if let fetchedChat = try? await fetchChat(oppUser: oppUser) {
self.chat = fetchedChat
}
}
}
init(chat: ChatModel) {
self.chat = chat
Task {
if let fetchedUser = try? await getOpposingUser(chat: chat) {
self.opposingUser = fetchedUser
}
}
}
@MainActor
func fetchChat(oppUser: User) async throws -> ChatModel? {
do {
let documents = try await Firestore.firestore()
.collection("conversations")
.whereField("users", arrayContains: UserService.shared.currentUser?.id ?? "error")
.whereField("users", arrayContains: oppUser.id)
.getDocuments()
for document in documents.documents {
guard let chatData = try? document.data(as: ChatModel.self) else {
print("[DEBUG fetchChat(oppUser: User)]: Error while converting Firebase Document to ChatModel ")
return nil
}
return chatData
}
} catch {
print("[DEBUG fetchChat(oppUser: User)]: \(error)")
throw error // Re-throw the error so it can be handled by the caller if needed
}
return nil
}
@MainActor
func getOpposingUser(chat: ChatModel) async throws -> User? {
do {
let opposingUid: String
if chat.users[0] == UserService.shared.currentUser?.id {
opposingUid = chat.users[1]
} else {
opposingUid = chat.users[0]
}
let document = try await Firestore
.firestore()
.collection("users")
.document(opposingUid)
.getDocument()
guard let opposingUserDoc = try? document.data(as: User.self) else {
// Handle the case where conversion to User fails
print("[DEBUG (getOpposingUser(chat: chatModel)]: Error while converting Firebase-Document to User ")
return nil
}
return opposingUserDoc
} catch {
print("[DEBUG (getOpposingUser(chat: chatModel)]: \(error) ")
throw error
}
return nil
}
} `
我尝试使用类似
self.chat = ChatModel()
的内容“预初始化”变量,但由于我的 Cahtmodel 的性质,我无法在没有属性的情况下初始化它。
chat
或opposingUser
)可选并分配nil。当这些数据来自 SwiftUI 视图时,您应该显示 nil
在 SwiftUI 视图中,您应该使用 ProgressView()
.task { await viewModel.fetchData() }
将异步获取数据并更新 @Published 变量。当您的 viewModel 的数据被获取时,它们将从 fetchData
更改为某个值。因此,当您的 nil
是 @StateObject 或 @ObservedObject 时,您的视图将自动重新加载。