【问题标题】:Simulator and iOS device tableView Firebase模拟器和iOS设备tableView Firebase
【发布时间】:2017-03-03 17:29:04
【问题描述】:

我正在制作一个聊天室应用。现在每个聊天帖子只能由发布它的用户看到。我如何使表格视图永久化并让所有用户不仅可以看到当前用户。就像实时提要一样。

我需要在所有设备上显示的示例,而不仅仅是测试设备:

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

【问题讨论】:

  • 模拟器无法接收通知。在两台真实设备上测试您的应用。
  • 你使用的是 Socket 还是 REST?
  • 也许我需要更好的解释。当我发送消息并将其发布到 UITableView 时,我如何将其永久保存在那里。因此,当有人在聊天室发帖时,它永远不会消失。
  • 上图是我需要他们永远留在那里让所有用户看到的消息示例
  • 我进行了编辑。当您发布消息时,它会在 tableView 上弹出。但只有发送消息的用户才能看到表格视图。我怎样才能让表格视图更像是一个实时提要,所以它就像一个聊天室。

标签: ios swift firebase firebase-realtime-database


【解决方案1】:

试试这个代码 - Obj-C

[[[self.reference child:@"general_room"] child:@"chat"] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {

    if (snapshot.value != (id)[NSNull null]) {

        NSArray *value = [snapshot.value allValues];

        NSLog(@"%@", [value valueForKey:@"Username"]);
        NSLog(@"%@", [value valueForKey:@"Message"]);
        NSLog(@"%@", [value valueForKey:@"photo_url"]);
    }

} withCancelBlock:^(NSError * _Nonnull error) {
    NSLog(@"%@", error.localizedDescription);
}];

迅速

检查语法不确定快速语法

    ref.child("general_room").child("chat").observeSingleEvent(of: .value, with: { (snapshot) in

    let value = snapshot.value as? NSArray

    for (dict in value) {
    let username = dict?["Username"] as? String
    let message = dict?["Message"] as? String
    let photo_url = dict?["photo_url"] as? String

        print(username)
        print(message)
        print(photo_url)

    }
    }) { (error) in
        print(error.localizedDescription)
    }}

【讨论】:

    猜你喜欢
    • 2021-05-15
    • 1970-01-01
    • 2019-01-10
    • 2013-05-24
    • 2012-12-31
    • 2012-05-17
    • 2018-08-29
    • 1970-01-01
    • 2021-05-25
    相关资源
    最近更新 更多