模拟器和iOS设备tableView Firebase [英] Simulator and iOS device tableView Firebase

查看:198
本文介绍了模拟器和iOS设备tableView Firebase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个聊天室的应用程序。现在每个聊天帖子都只能被发布的用户看到。我如何使表视图永久,并为所有用户不仅看到当前用户。像一个活的饲料。



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

 导入UIKit 
导入基础
导入Firebase
导入FirebaseDatabase
导入FirebaseStorage

结构postStruct {
让用户名:字符串!
让消息:字符串!
让photoURL:String!


class GeneralChatroom:UIViewController,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate {

@IBOutlet弱var messageTextField:UITextField!

var generalRoomDataArr = [postStruct]()

@IBOutlet weak var tableView:UITableView!
$ b $重写func viewDidLoad(){
super.viewDidLoad()

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 140



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



$ b 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),在:0)
self.tableView.reloadData()

})

}


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









//消息发送按钮被按下的数据上传到firebase
@IBAction func sendButtonPressed(_ sender:UIButton){

let message:String = self.messageTextField.text!

UploadGeneralChatRoom(message:message)//上传到general_room

self.messageTextField.text = nil
messageTextField.resignFirstResponder()//退出键盘
self.tableView.reloadData()//重新载入tableView
// UploadUserData()//更新数据库中的排序


func tableView(_ tableView:UITableView,numberOfRowsInSection section :Int) - > Int {
return generalRoomDataArr.count //您在这里的单元格数量
}

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 //换行$ b $ messageLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
messageLabel.text = generalRoomDataArr [indexPath.row] .message



//初始化UI配置文件映像
让imageView = cell?.viewWithTag(3)as! UIImageView

//制作Porfile图片Cirlce
imageView.layer.cornerRadius = imageView.frame.size.width / 2
imageView.clipsToBounds = true

// tableview中的用户个人资料图片
如果generalRoomDataArr [indexPath.row] .photoURL!= nil
{
//让imageView = cell?.viewWithTag(3)as! UIImageView
$ b如果让url = NSURL(string:generalRoomDataArr [indexPath.row] .photoURL){

如果让data = NSData(contentsOf:url作为URL){

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







//你的单元格编码
返回单元格!


$ b} // END CLASS


解决方案

试试这段代码 - Obj-C

  [[[self.reference child: @general_room] child:@chat] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot){
$ b $ 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);
}];

在swift中



不知道关于swift语法

  ref.child(general_room)。child(chat)。observeSingleEvent(。值,其中:{(snapshot)in 

let value = snapshot.value as?NSArray

for(dict in value){
let username = dict?字符串
让message = dict?[Message] as?字符串
让photo_url = dict?[photo_url] as?字符串

打印(用户名)
打印(消息)
打印(photo_url)

$ b}){(错误)在
打印(error.localizedDescription)
}}


I am making a chat room app. Right now every chat post can only be seen by the user who posted it. How do i make the table view permanent and for all users to see not just the current user. Like a live feed.

Exaple of what i need to show on all devices not just the test device:

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

解决方案

Try this code - 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);
}];

In swift

Check with syntax am not sure about swift syntax

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

这篇关于模拟器和iOS设备tableView Firebase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆