异步初始化器 Swift MVVM 不工作

问题描述 投票:0回答:1

嗨,有人可以帮助我吗?我真的很难让这些初始化工作。由于任务我总是被 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 的性质,我无法在没有属性的情况下初始化它。

swift swiftui mvvm async-await
1个回答
0
投票
  1. 首先使您的数据(例如
    chat
    opposingUser
    )可选并分配nil。当这些数据来自 SwiftUI 视图时,您应该显示
    nil
    在 SwiftUI 视图中,您应该使用 
  2. ProgressView()
  3. 开始获取数据,该视图将在视图 onAppear 期间调用。函数
    .task { await viewModel.fetchData() }
    将异步获取数据并更新 @Published 变量。当您的 viewModel 的数据被获取时,它们将从
    fetchData
    更改为某个值。因此,当您的
    nil
    是 @StateObject 或 @ObservedObject 时,您的视图将自动重新加载。
    
    
  4. 注意:我无法共享代码,因为您尚未共享完整的可构建代码。

© www.soinside.com 2019 - 2024. All rights reserved.