ios - Firebase数据库误读

标签 ios swift firebase firebase-realtime-database

我的用户名数据突然停止显示。这是否有什么非常奇怪的地方,或者我只是误读了我的代码。之前可以用,但现在突然停止输出用户名了。

enter image description here

enter image description here

enter image description here

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



import UIKit
import Foundation
import Firebase
import FirebaseDatabase
import FirebaseStorage
import AlamofireImage
import Alamofire

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



class GeneralChatroom: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {

    @IBOutlet weak var messageTextField: UITextField!
    @IBOutlet weak var tableView: UITableView!



    var generalRoomDataArr = [postStruct]()


    override func viewDidLoad() {
        super.viewDidLoad()


        //TableView Cell word wrap (Dynamic Text)
        self.tableView.dataSource = self
        self.tableView.delegate = self
        self.tableView.estimatedRowHeight = 78
        self.tableView.rowHeight = UITableViewAutomaticDimension






        let ref = FIRDatabase.database().reference()
        //let userID = FIRAuth.auth()?.currentUser?.uid


        ref.child("general_room").queryOrderedByKey().observe(.childAdded, with: {snapshot in

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

            print("username: " + username)
            print("message: " + message)

            //Time String from Firbase Database
            let timeString = snapDict?["time_stamp"] as? String ?? "2017-03-06 00:20:51"

            //timeAgoSinceDate - Format and call function to recieve time of post
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            let timeStampDate = dateFormatter.date(from: timeString)
            let timeStamp = timeAgoSinceDate(date: timeStampDate!, numericDates: false)


            //Assign array values
            self.generalRoomDataArr.insert(postStruct(username: username, message: message, photoURL: firebaseUserPhotoURL, timeStamp: timeStamp), 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) {



        //If a character exists will be uploaded to firebase
        if ((messageTextField.text?.characters.count)! > 0) {

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

        //Transform Data From ^ to load at the bottom
        tableView.transform = CGAffineTransform (scaleX: 1,y: -1);
        cell?.contentView.transform = CGAffineTransform (scaleX: 1,y: -1);
        cell?.accessoryView?.transform = CGAffineTransform (scaleX: 1,y: -1);


//        tableView.backgroundColor = UIColor.white
//        tableView.layer.cornerRadius = 3.0
//        tableView.layer.masksToBounds = false
//        tableView.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor
//        tableView.layer.shadowOffset = CGSize(width: 0, height: 0)
//        tableView.layer.shadowOpacity = 0.8




//        cell?.contentView.backgroundColor = UIColor.clear
//        
//        let whiteRoundedView : UIView = UIView(frame: CGRect(x: 10, y: 8, width: self.view.frame.size.width - 20, height: 120))
//        
//        whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [1.0, 1.0, 1.0, 0.9])
//        whiteRoundedView.layer.masksToBounds = false
//        whiteRoundedView.layer.cornerRadius = 3.0
//        whiteRoundedView.layer.shadowOffset = CGSize(width: 0, height: 0)
//        whiteRoundedView.layer.shadowOpacity = 0.2
//        
//        cell?.contentView.addSubview(whiteRoundedView)
//        cell?.contentView.sendSubview(toBack: whiteRoundedView)
//        






//

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


        //Set message label to display message
        let messageLabel = cell?.viewWithTag(2) as! UILabel
        messageLabel.text = generalRoomDataArr[indexPath.row].message
        messageLabel.numberOfLines = 0

        //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

        //Set timeStampLabel to current time AGO
        let timeStampLabel = cell?.viewWithTag(4) as! UILabel
        timeStampLabel.text = generalRoomDataArr[indexPath.row].timeStamp
        timeStampLabel.numberOfLines = 0

        //Loading and change of Usesrs profile image on chat cell
        let userProfileChatImage = generalRoomDataArr[indexPath.row].photoURL

        //Load profile image(on cell) with URL & Alamofire Library
        let downloadURL = NSURL(string: userProfileChatImage!)
        imageView.af_setImage(withURL: downloadURL as! URL)

        // your cell coding
        return cell!
    }




    //                      KeyBoard (move text box above keyboard)




    // Start Editing The Text Field
    func textFieldDidBeginEditing(_ messageTextField: UITextField) {
        moveTextField(messageTextField, moveDistance: -250, up: true)
    }

    // Finish Editing The Text Field
    func textFieldDidEndEditing(_ messageTextField: UITextField) {
        moveTextField(messageTextField, moveDistance: -250, up: false)
    }

    // Hide the keyboard when the return key pressed
    func textFieldShouldReturn(_ messageTextField: UITextField) -> Bool {
        messageTextField.resignFirstResponder()
        return true
    }

    // Move the text field in a pretty animation!
    func moveTextField(_ messageTextField: UITextField, moveDistance: Int, up: Bool) {
        let moveDuration = 0.3
        let movement: CGFloat = CGFloat(up ? moveDistance : -moveDistance)

        UIView.beginAnimations("animateTextField", context: nil)
        UIView.setAnimationBeginsFromCurrentState(true)
        UIView.setAnimationDuration(moveDuration)
        self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)
        UIView.commitAnimations()
    }


}//END CLASS

最佳答案

前言:由于代表的原因,我还不能发表简单的评论。正如 Ro4ch 提到的,检查身份验证规则很重要。不过,您可以验证 snapshot.key 值是否与 Firebase 控制台上的值相同。

我假设 Kebtfc...general_room 的子级。如果是这样的话。那么该快照将是用户快照的数组,对吗?您需要这样解析它。

关于ios - Firebase数据库误读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42643706/

相关文章:

ios - 如何等待另一个值被分配来运行.onAppear?

firebase - Flutter参数类型 'Object?'无法分配给参数类型 'Map<String, dynamic>'

java - Firebase 连接不可用 Android Studio 3.2

android - Firebase session 失效

javascript - iOS WKWebview 未响应 <a href ="javascript:doSomething()"...></a> 上的点击事件

ios - 下载图像后,在自定大小的 tableview 单元中重新加载约束或更新高度

iphone - iOS Core Graphics 填充路径的反转?

ios - 当 UIImageView 显示图像时,如何防止 UIToolbar 调整大小?

java - 如何在 Java 中创建静态模型?

ios - table view 行可以在其部分移动时保持原样吗?