如何在Firebase中获取值的键?
我用的是Swift 3 我有一个类似twitter的社交网络,我试图检索用户的以下列表,但我遇到了一些麻烦,我的想法是获取它们,这样我就可以使用它们进行for循环并检索帖子或tweet,类似这样的事情如何在Firebase中获取值的键?,firebase,swift3,firebase-realtime-database,Firebase,Swift3,Firebase Realtime Database,我用的是Swift 3 我有一个类似twitter的社交网络,我试图检索用户的以下列表,但我遇到了一些麻烦,我的想法是获取它们,这样我就可以使用它们进行for循环并检索帖子或tweet,类似这样的事情 self.databaseRef.child("following").child((self.loggedInUser?.uid)!).observeSingleEvent(of: .value) { (snapshot:FIRDataSnapshot) in
self.databaseRef.child("following").child((self.loggedInUser?.uid)!).observeSingleEvent(of: .value) { (snapshot:FIRDataSnapshot) in
for child in snapshot.children {
self.databaseRef.child("Jalas").child((child as AnyObject).key!).observe(.childAdded, with: { (snapshot:FIRDataSnapshot) in
if (snapshot.value as? NSDictionary != nil)
{
self.Jalas.append(snapshot.value as! NSDictionary)
}
}){(error) in
print(error.localizedDescription)
}
}
self.homeTableView.beginUpdates()
self.homeTableView.insertRows(at: [IndexPath(row:0,section:0)], with: UITableViewRowAnimation.automatic)
self.homeTableView.endUpdates()
self.aivLoading.stopAnimating()
}
在节中的行数中,我返回self.Jalas.count,但这没有任何作用。这给了我一个错误
尝试将行0插入节0,但更新后节0中只有0行 这是我的数据库 Jalas=员额 这是我的全部代码
//
// HomeViewController.swift
// Twitter Clone
//
// Created by Juan Carlos Estevez on 15/12/16.
// Copyright © 2016 JC&C. All rights reserved.
//
import UIKit
import FirebaseDatabase
import FirebaseAuth
import SDWebImage
import ReadMoreTextView
class HomeViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate {
var databaseRef = FIRDatabase.database().reference()
var loggedInUser:AnyObject?
var loggedInUserData:NSDictionary?
var listFollowing = [NSDictionary?]()
var listFollowers = [NSDictionary?]()//store all the followers
@IBOutlet weak var aivLoading: UIActivityIndicatorView!
@IBOutlet weak var homeTableView: UITableView!
var defaultImageViewHeightConstraint:CGFloat = 77.0
var Jalas = [NSDictionary]()
override func viewDidLoad() {
super.viewDidLoad()
self.homeTableView.separatorStyle = .none
//self.homeTableView.backgroundView?.backgroundColor = UIColor.init(red: 247, green: 247, blue: 247, alpha: 1)
UITabBar.appearance().tintColor = UIColor.orange
navigationController?.navigationBar.barTintColor = UIColor.orange
Evento.sharedInstance.titulo = ""
Evento.sharedInstance.UbicacionN = nil
self.loggedInUser = FIRAuth.auth()?.currentUser
self.databaseRef.child("following").child((self.loggedInUser?.uid)!).observeSingleEvent(of: .value) { (snapshot:FIRDataSnapshot) in
for child in snapshot.children {
self.databaseRef.child("Jalas").child((child as AnyObject).key!).observeSingleEvent(of: .value) { (snapshot:FIRDataSnapshot) in
//if (snapshot.value as? NSDictionary != nil)
//{
self.Jalas.append(snapshot.value as! NSDictionary)
//}
}
}
//self.homeTableView.beginUpdates()
self.homeTableView.insertRows(at: [IndexPath(row:0,section:0)], with: UITableViewRowAnimation.automatic)
//self.homeTableView.endUpdates()
self.aivLoading.stopAnimating()
}
/*
//get the logged in users details
self.databaseRef.child("user_profiles").child(self.loggedInUser!.uid).observeSingleEvent(of: .value) { (snapshot:FIRDataSnapshot) in
//store the logged in users details into the variable
self.logdInUserData = snapshot.value as? NSDictionary
// print(self.loggedInUserData)
//get all the Jalas that are made by the user
self.databaseRef.child("Jalas").child(self.loggedInUser!.uid).observe(.childAdded, with: { (snapshot:FIRDataSnapshot) in
//self.Jalas.append(snapshot.value as! NSDictionary)
self.homeTableView.insertRows(at: [IndexPath(row:0,section:0)], with: UITableViewRowAnimation.automatic)
self.aivLoading.stopAnimating()
}){(error) in
print(error.localizedDescription)
}
}
*/
//when the user has no posts, stop animating the aiv after 5 seconds
Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(stopAnimating), userInfo: nil, repeats: false)
self.homeTableView.rowHeight = UITableViewAutomaticDimension
self.homeTableView.estimatedRowHeight = 140
/*
self.databaseRef.child("following").child(self.loggedInUser!.uid).observe(.childAdded, with: { (snapshot) in
let snapshot = snapshot.value as? NSDictionary
self.listFollowing.append(snapshot)
print(self.listFollowing)
}) { (error) in
print(error.localizedDescription)
}
self.databaseRef.child("followers").child(self.loggedInUser!.uid).observe(.childAdded, with: { (snapshot) in
let snapshot = snapshot.value as? NSDictionary
self.listFollowers.append(snapshot)
print(self.listFollowers)
}) { (error) in
print(error.localizedDescription)
}
*/
}
@IBAction func NewJalo(_ sender: Any) {
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let welcomeViewController: UIViewController = mainStoryboard.instantiateViewController(withIdentifier: "new")
self.present(welcomeViewController, animated: true, completion: nil)
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UITabBar.appearance().tintColor = UIColor.orange
return true
}
open func stopAnimating()
{
self.aivLoading.stopAnimating()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.Jalas.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
tableView.separatorStyle = .none
var ubicacion = ""
let cell: HomeViewTableViewCell = tableView.dequeueReusableCell(withIdentifier: "HomeViewTableViewCell", for: indexPath) as! HomeViewTableViewCell
cell.contentView.backgroundColor = UIColor.clear
let JaloPost = Jalas[(self.Jalas.count-1) - (indexPath.row)]["text"] as! String
var HG = 105
let CHAR = JaloPost.characters.count
if (CHAR > 30)
{
let CH = ((CHAR/30) * 15)
HG += CH
}
if(Jalas[(self.Jalas.count-1) - (indexPath.row)]["picture"] != nil)
{
HG += 77
}
let whiteRoundedView : UIView = UIView(frame: CGRect(x: 10, y: 8, width: Int(self.view.frame.size.width - 20), height: HG))
whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [1.0, 1.0, 1.0, 0.9])
whiteRoundedView.layer.masksToBounds = false
whiteRoundedView.layer.cornerRadius = 2.0
whiteRoundedView.layer.shadowOffset = CGSize(width: -1, height: 1)
whiteRoundedView.layer.shadowOpacity = 0.2
cell.contentView.addSubview(whiteRoundedView)
cell.contentView.sendSubview(toBack: whiteRoundedView)
let imageTap = UITapGestureRecognizer(target: self, action: #selector(self.didTapMediaInTweet(_:)))
cell.tweetImage.addGestureRecognizer(imageTap)
if(Jalas[(self.Jalas.count-1) - (indexPath.row)]["ubicacionN"] != nil)
{
ubicacion = (Jalas[(self.Jalas.count-1) - (indexPath.row)]["ubicacionN"] as? String)!
}
if(Jalas[(self.Jalas.count-1) - (indexPath.row)]["picture"] != nil)
{
cell.tweetImage.isHidden = false
cell.imageViewHeightConstraint.constant = defaultImageViewHeightConstraint
let picture = Jalas[(self.Jalas.count-1) - (indexPath.row)]["picture"] as! String
let url = URL(string:picture)
cell.tweetImage.layer.cornerRadius = 10
cell.tweetImage.layer.borderWidth = 3
cell.tweetImage.layer.borderColor = UIColor.clear.cgColor
cell.tweetImage!.sd_setImage(with: url, placeholderImage: UIImage(named:"twitter")!)
}
else
{
cell.tweetImage.isHidden = true
cell.imageViewHeightConstraint.constant = 0
}
if (self.loggedInUserData!["profile_pic"] == nil)
{
cell.configure(nil,name:self.loggedInUserData!["name"] as! String,handle:self.loggedInUserData!["handle"] as! String,tweet:JaloPost, ubi: ubicacion)
}else
{
cell.configure(self.loggedInUserData!["profile_pic"]! as? String,name:self.loggedInUserData!["name"] as! String,handle:self.loggedInUserData!["handle"] as! String,tweet:JaloPost, ubi: ubicacion)
}
return cell
}
func didTapMediaInTweet(_ sender:UITapGestureRecognizer)
{
let imageView = sender.view as! UIImageView
let newImageView = UIImageView(image: imageView.image)
newImageView.frame = self.view.frame
newImageView.backgroundColor = UIColor.black
newImageView.contentMode = .scaleAspectFit
newImageView.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target:self,action:#selector(self.dismissFullScreenImage))
newImageView.addGestureRecognizer(tap)
self.view.addSubview(newImageView)
}
func dismissFullScreenImage(_ sender:UITapGestureRecognizer)
{
sender.view?.removeFromSuperview()
}
/*
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "findUserSegue")
{
var showFollowingTableViewController = segue.destination as! FollowUsersTableViewController
showFollowingTableViewController.loggedInUser = self.loggedInUser as? FIRUser
// showFollowingTableViewController.followData = self.followData
}
else if(segue.identifier == "showFollowersTableViewController")
{
var showFollowersTableViewController = segue.destination as! ShowFollowersTableViewController
showFollowersTableViewController.user = self.loggedInUser as? FIRUser
}
}
*/
}
这是我的表视图单元格代码
//
// HomeViewTableViewCell.swift
// Jalo
//
// Created by Juan Carlos Estevez Rodriguez on 24/08/16.
// Copyright © 2016 JC&C. All rights reserved.
//
import UIKit
open class HomeViewTableViewCell: UITableViewCell {
@IBOutlet weak var profilePic: UIImageView!
@IBOutlet weak var name: UILabel!
@IBOutlet weak var handle: UILabel!
@IBOutlet weak var tweet: UITextView!
@IBOutlet weak var tweetImage: UIImageView!
@IBOutlet weak var ubic: UILabel!
@IBOutlet weak var imageViewHeightConstraint: NSLayoutConstraint!
override open func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
open func configure(_ profilePic:String?,name:String,handle:String,tweet:String, ubi:String)
{
self.tweet.text = tweet
self.handle.text = "@"+handle
self.name.text = name
self.ubic.text = ubi
if((profilePic) != nil)
{
let imageData = try? Data(contentsOf: URL(string:profilePic!)!)
self.profilePic.image = UIImage(data:imageData!)
}
else
{
self.profilePic.image = UIImage(named:"twitter")
}
}
}
这个
分段是最有可能导致您的问题的原因。在编辑问题并添加准确的错误之前,您无法确定
在UITableView中使用
.insertRows()
时,需要确保numberOfRows方法中的计数也会相应更改。这里的问题只是委托方法返回的行数与实际行数不匹配。确保使用.insertRows()
时,在委托方法中返回新的预期行数 返回self.Jalas.count
时抛出了什么错误?我感觉您没有设置表视图委托/数据源方法我添加了我的全部代码,我想我已经添加了,但请查看jahahahaha@LucasChwelooks,就像您已经启动了这些方法一样,但我认为您没有设置委托和数据源。类似于self.homeTableView.delegate=self;和self.homeTableView.dataSource=self;在viewDidLoad中应该这样做,我不认为您只想插入一行,我认为您最好只调用reloadData而不是insertRows:没关系!我们都必须从某个地方开始:-)那个错误表明了我的怀疑。您只需在一个部分中返回与实际不同的特定行数。因此,在使用.insertRows(at:…,with:…)
之前,请确保在self.Jalas
中添加新元素,以便self.Jalas.count
在表中具有相同的行数。他们必须匹配!如果您不明白,请告诉我,这样我就可以更新我的答案并添加一个示例,可能会尝试将第0行插入节0,但在更新后,节0中只有0行,这就是我得到的错误。所以我要做的就是@ReunderTruct,对不起,我对swift很陌生
//
// HomeViewTableViewCell.swift
// Jalo
//
// Created by Juan Carlos Estevez Rodriguez on 24/08/16.
// Copyright © 2016 JC&C. All rights reserved.
//
import UIKit
open class HomeViewTableViewCell: UITableViewCell {
@IBOutlet weak var profilePic: UIImageView!
@IBOutlet weak var name: UILabel!
@IBOutlet weak var handle: UILabel!
@IBOutlet weak var tweet: UITextView!
@IBOutlet weak var tweetImage: UIImageView!
@IBOutlet weak var ubic: UILabel!
@IBOutlet weak var imageViewHeightConstraint: NSLayoutConstraint!
override open func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
open func configure(_ profilePic:String?,name:String,handle:String,tweet:String, ubi:String)
{
self.tweet.text = tweet
self.handle.text = "@"+handle
self.name.text = name
self.ubic.text = ubi
if((profilePic) != nil)
{
let imageData = try? Data(contentsOf: URL(string:profilePic!)!)
self.profilePic.image = UIImage(data:imageData!)
}
else
{
self.profilePic.image = UIImage(named:"twitter")
}
}
}
self.homeTableView.beginUpdates()
self.homeTableView.insertRows(at: [IndexPath(row:0,section:0)], with: UITableViewRowAnimation.automatic)
self.homeTableView.endUpdates()