You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift iOS中如何将completion handler传递给其他函数(Firebase聊天场景)

问题原因

核心错误是setValue回调的判断逻辑完全写反:Firebase Realtime Database 的setValue异步回调中,error参数为nil代表写入操作成功,不为nil才代表写入出错。
你当前代码的判断逻辑是guard error != nil else {return},即写入成功时直接退出回调,永远不会执行后续创建消息节点的逻辑,只有写入失败时才会调用后续方法,所以只会生成会话节点,不会生成对应的消息节点。

修复方案

1. 修改insertConversation2中的两处setValue回调逻辑

两处回调的判断都需要修正,成功时才调用finishCreatingConversation,失败时直接返回错误:

// 原来的错误逻辑
// database.child("\(getSafeEmail)").setValue(userNode) { (error, ref) in
//     guard error != nil else {return}
//     self.finishCreatingConversation(conversationId: conversationId, message: message, completion: completion)
// }

// 修改后的正确逻辑
database.child("\(getSafeEmail)").setValue(userNode) { (error, ref) in
    guard error == nil else {
        completion(false)
        print("会话节点写入失败: \(error!.localizedDescription)")
        return
    }
    self.finishCreatingConversation(conversationId: conversationId, message: message, completion: completion)
}

注意insertConversation2中有两处相同的回调,都需要做上述修改。

2. 同步修改finishCreatingConversation中的setValue回调逻辑

第二个函数的回调也存在同样的逻辑错误,修改为:

// 原来的错误逻辑
// database.child("\(conversationId)").setValue(collectionMessge) { (error, ref) in
//     guard error != nil else {return}
//     completion(true)
// }

// 修改后的正确逻辑
database.child("\(conversationId)").setValue(collectionMessge) { (error, ref) in
    guard error == nil else {
        completion(false)
        print("消息节点写入失败: \(error!.localizedDescription)")
        return
    }
    completion(true)
}

额外检查项

如果修改后仍然有问题,可以排查以下两点:

  • 检查Firebase Realtime Database的安全规则,是否开放了对应路径的写入权限
  • 确认getUserEmail方法处理后的邮箱没有非法字符,不会导致路径解析错误

内容的提问来源于stack exchange,提问作者Faheem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 14:12:02