[英]Firebase Database Count
What is the best way to add a count to your chat messages to upload to googles firebase database? 在聊天消息中添加计数以上传到Google Firebase数据库的最佳方法是什么? The way I have it the count keeps geting re-initialized so it messes up the data.
我用的方法是,计数不断重新初始化,因此弄乱了数据。
QUESTION: What is the best way to upload chat messages so that they do not interfere with each other? 问题:上载聊天消息以免彼此干扰的最佳方法是什么? via firebase.
通过firebase。
+general_room 1,2,3,4 + general_room 1,2,3,4
numbers representing each messaga sent. 代表发送的每个messaga的数字。
import Foundation
import Firebase
import FirebaseDatabase
import FirebaseStorage
var count = 0
func UploadGeneralChatRoom(message : String) {
//Firebase Initialization
var ref: FIRDatabaseReference!
//var storage: FIRStorageReference!
let userID = FIRAuth.auth()?.currentUser?.uid
ref = FIRDatabase.database().reference()
//storage = FIRStorage.storage().reference()
//Get Data from database resend to database
ref.child("Users").child(userID!).observeSingleEvent(of: .value, with: {(snapshot) in
let snapDict = snapshot.value as? NSDictionary
let username = snapDict?["Username"] as? String ?? ""
let firebaseUserPhotoURL = snapDict?["photo_url"] as? String ?? ""
count = count + 1
print("Count: ", count)
let countString = String(count)
print("CountStrig: " + countString)
ref.child("general_room").child(countString).setValue(["Username": username, "uid": userID!, "Message" : message, "photo_url" : firebaseUserPhotoURL])
})
}
The original question is pretty unclear but if you want to upload a message to a chat room, here's a structure: 最初的问题尚不清楚,但是如果您要将消息上传到聊天室,则结构如下:
users
uid_0
name: "Kirk"
uid_1
name: "Spock"
uid_2
name: "McCoy"
chat_rooms
room_0
name: "Bridge Chat Room"
messages:
message_0:
msg: "This is a message posted by Spock"
uid: "uid_1"
message_1:
msg: "Message posted by Kirk"
uid: "uid_0"
and some code to create a new message in chat_rooms, room_0 (this could be greatly condensed but leaving verbose for readability) 以及一些用于在chat_rooms,room_0中创建新消息的代码(可能会被压缩,但为了便于阅读而显得冗长)
let ref = rootRef.child("chat_rooms")
let roomRef = ref.child("room_0")
let messagesRef = roomRef.child("messages")
let msgRef = messagesRef.childByAutoId()
let data = ["msg": "a message posted by McCoy",
"uid": "uid_2"]
msgRef.setValue(data)
will result in 将导致
chat_rooms
room_0
name: "Bridge Chat Room"
messages:
message_0:
msg: "This is a message posted by Spock"
uid: "uid_1"
message_1:
msg: "Message posted by Kirk"
uid: "uid_0"
message_2:
msg: "a message posted by McCoy"
uid: "uid_2"
message_0, message_1 etc are keys created with childByAutoId. message_0,message_1等是使用childByAutoId创建的键。
If you want to know how many messages there are, here's one option 如果您想知道有多少条消息,这是一种选择
messagesRef.observeSingleEvent(of: .value, with: { snapshot in
print(snapshot.childrenCount)
})
and the result 和结果
3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.