ios - TableView 对所有用户公开

标签 ios swift firebase firebase-realtime-database

我正在创建一个聊天室应用程序。目前,当用户登录时,他们也会获得自己的表格 View 来上传数据。

我希望所有用户都连接到一个(公共(public))表格 View ,而不是每个用户都有自己的个人表格 View ,以便每个人都可以看到发布的内容。因此就有了聊天室应用程序。

  • 这是 3 个单独的登录信息以及每个用户发布消息时的情况:

3 Seperate users when logging in and posting to the Tableview

  • 这就是我想要的。让每个表格 View 单元格代表来自不同用户的不同消息。所有内容均在一个桌面 View 上公开查看。不在单独的 TableView 上:

What I want the tableView to do when a user posts

如何公开 TableView ?当我以其他用户身份登录时,我希望每个用户仍然保留之前的消息。因此就有了一个聊天室。

enter image description here

{
   "rules": {
  "Users":{
     ".read": "true",
     ".write": "true"
},
  "general_room" : {
    ".read": "true",
     ".write": "true"
  }
    }
}

GeneralChatroom.swift

import UIKit
import Foundation
import Firebase
import FirebaseDatabase
import FirebaseStorage

struct postStruct {
    let username : String!
    let message : String!
    let photoURL : String!
}

class GeneralChatroom: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {

    @IBOutlet weak var messageTextField: UITextField!

    var generalRoomDataArr = [postStruct]()

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 140


        let ref = FIRDatabase.database().reference()
        let userID = FIRAuth.auth()?.currentUser?.uid            
        ref.child("general_room").child("chat").child(userID!).queryOrderedByKey().observe(.childAdded, with: {snapshot in

            let snapDict = snapshot.value as? NSDictionary
            let username = snapDict?["Username"] as? String ?? ""
            let message = snapDict?["Message"] as? String ?? ""
            let firebaseUserPhotoURL = snapDict?["photo_url"] as? String ?? ""

            self.generalRoomDataArr.insert(postStruct(username: username, message: message, photoURL: firebaseUserPhotoURL), at: 0)
            self.tableView.reloadData()

        })

    }

    @IBAction func backButtonPressed(_ sender: UIButton) {
        self.performSegue(withIdentifier: "BackToRoom", sender: nil)
    }    

    //Message Send button is pressed data uploaded to firebase
    @IBAction func sendButtonPressed(_ sender: UIButton) {

        let message : String = self.messageTextField.text!

        UploadGeneralChatRoom(message: message) //upload to general_room

        self.messageTextField.text = nil
        messageTextField.resignFirstResponder()//Quit keyboard
        self.tableView.reloadData() //Reload tableView
        //UploadUserData() //Update Rank in database
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return generalRoomDataArr.count // your number of cell here
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")

        let usernameLabel = cell?.viewWithTag(1) as! UILabel
        usernameLabel.text = generalRoomDataArr[indexPath.row].username

        let messageLabel = cell?.viewWithTag(2) as! UILabel
        messageLabel.numberOfLines=0 // line wrap
        messageLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
        messageLabel.text = generalRoomDataArr[indexPath.row].message


        //initialize UI Profile Image
        let imageView = cell?.viewWithTag(3) as! UIImageView

        //Make Porfile Image Cirlce
        imageView.layer.cornerRadius = imageView.frame.size.width/2
        imageView.clipsToBounds = true

        //User Profile image in tableview
        if generalRoomDataArr[indexPath.row].photoURL != nil
        {
            //let imageView = cell?.viewWithTag(3) as! UIImageView

            if let url = NSURL(string: generalRoomDataArr[indexPath.row].photoURL) {

                if let data = NSData(contentsOf: url as URL) {

                    imageView.image = UIImage(data: data as Data)
                }
            }
        }

        // your cell coding
        return cell!
    }       

}//END CLASS

上传到 firebase

import Foundation
import Firebase
import FirebaseDatabase
import FirebaseStorage

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 ?? ""           
        ref.child("general_room").child("chat").child(userID!).childByAutoId().setValue(["Username": username, "uid": userID!, "Message" : message, "photo_url" : firebaseUserPhotoURL])

    })        
}

最佳答案

我不知道您的 Firebase 数据库是如何设置的,但您正在发布到 child("Users").child(userID!) 但读自 child("general_room").child("chat").child(userID!)

您需要读取和写入同一位置。

另外: 尝试安全地解开您的可选值:

if let userId = userID {
    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 ?? ""

            ref.child("general_room").child("chat").child(userID!).childByAutoId().setValue(["Username": username, "uid": userID!, "Message" : message, "photo_url" : firebaseUserPhotoURL])
     })
}

关于ios - TableView 对所有用户公开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42571815/

相关文章:

ios - 无法在设备上运行单元测试 - 代码覆盖数据生成失败 (IOS)

ios - 如何在 swift 中使用委托(delegate)通知 UIViewController 在 xib 文件中单击了一个按钮?

objective-c - CIAreaHistogram 给了我除了最后一个元素之外的所有 0?

javascript - 使用 React Redux Redux-Thunk 进行 Firebase 身份验证

java - 如果文档使用大型 Map 字段,则 Firebase Firestore 查询错误

android - Firebase 在实时数据库发生变化时发送通知

ios - 仅使用 LayoutConstraints 来更改方向?

ios - UIApplicationInvalidInterfaceOrientation 问题

ios - 为网站指定 iOS 跳板图标的所有方法

Swift二维字典错误