Firebase数据库计数

时间:2017-03-02 16:57:33

标签: ios firebase firebase-realtime-database

在聊天消息中添加计数以上传到googles firebase数据库的最佳方法是什么?我有它的方式计数保持重新初始化,所以它弄乱了数据。

问题:上传聊天消息的最佳方式是什么,以免互相干扰?通过firebase。

+ general_room   1,2,3,4-

代表每个发送的消息的数字。

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])


    })

}

1 个答案:

答案 0 :(得分:0)

最初的问题还不清楚,但如果你想将信息上传到聊天室,这里有一个结构:

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"

以及一些在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)

将导致

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等是使用childByAutoId创建的密钥。

如果你想知道有多少条消息,这里有一个选项

messagesRef.observeSingleEvent(of: .value, with: { snapshot in
    print(snapshot.childrenCount)
})

和结果

3