傳送訊息
打開ChatViewController.swift,在override func didReceiveMemoryWarning() {}之後加入
override func senderId() -> String {
return FIRAuth.auth()?.currentUser?.uid ?? ""
}
override func senderDisplayName() -> String {
return FIRAuth.auth()?.currentUser?.displayName ?? FIRAuth.auth()?.currentUser?.email ?? ""
}
override func didPressSend(_ button: UIButton, withMessageText text: String, senderId: String, senderDisplayName: String, date: Date) {
// TODO: 實作傳送訊息
}
senderId、senderDisplayName為JSQMessagesViewController必須自己實作的func,若沒有實作會在按下送出訊息時Crash
實作傳送訊息的部分
override func didPressSend(_ button: UIButton, withMessageText text: String, senderId: String, senderDisplayName: String, date: Date) {
// 實作傳送訊息
let messageNode = messageRef.childByAutoId()
let message = [
"senderId": senderId,
"senderDisplayName": senderDisplayName,
"date": date.timeIntervalSince1970,
"text": text
] as [String : Any];
self.messages.append(message)
messageNode.setValue(message) {[weak self] (error, _) in
self?.finishSendingMessage()
}
}
運行APP,傳送幾個訊息並觀察Database的變化,目前Database結構如下
程式碼儲存點