【问题标题】:Retrieving Data in a specific order from Firebase swift 4从 Firebase swift 4 按特定顺序检索数据
【发布时间】:2017-11-20 21:31:07
【问题描述】:

我创建了一个小应用程序,用户可以将post 上传到 firebase 数据库,然后在表格视图中,所有用户的内容都显示得很像 Instagram。我遇到了一个小问题:用户的posts 是按字母顺序显示的,而不是按最新上传的posts 显示在tableview 开头的顺序。

这是我从 firebase 下载数据并在我的tableView 中查看的代码。有谁知道出了什么问题,或者为什么帖子按字母顺序显示?

import UIKit
import FirebaseStorage
import FirebaseDatabase
import FirebaseAuth
import FirebaseCore
import Firebase

class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var postsTableView: UITableView!

var posts = NSMutableArray()

override func viewDidLoad() {
    super.viewDidLoad()

    loadData()

    self.postsTableView.delegate = self
    self.postsTableView.dataSource = self

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


func loadData() {
    Database.database().reference().child("posts").observeSingleEvent(of: .value) { (snapshot) in
        if let postsDictionary = snapshot.value as? [String: AnyObject] {
        for post in postsDictionary {
            self.posts.add(post.value)

            }
            self.postsTableView.reloadData()
        }
    }
}

// MARK: - Table view data source

 func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return self.posts.count
}


 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! PostTableViewCell
    // Configure the cell...
    let post = self.posts[indexPath.row] as! [String: AnyObject]
    cell.titleLabel.text = post["title"] as? String
    cell.contentTextView.text = post["content"] as? String

        if let imageName = post["image"] as? String {

            let imageRef = Storage.storage().reference().child("images/\(imageName)")
            imageRef.getData(maxSize: 25 * 1024 * 1024) { (data, error) -> Void in
                if error == nil {
                    //successfull
                    let downloadedImage = UIImage(data: data!)
                    cell.postsImageView.image = downloadedImage
                }else {
                    // error

                    print("there was an error downloading image: \(String(describing: error?.localizedDescription))")
            }
        }
    }

            return cell
        }


func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 400.0
}

@IBAction func logOutButton(_ sender: Any) {
    do {
    try Auth.auth().signOut()

        let registerSuccess = self.storyboard?.instantiateViewController(withIdentifier: "SignInVC")
        self.present(registerSuccess!, animated: true, completion: nil)
    }catch {

        let logInAlert = UIAlertController(title: "Ops something went wrong", message: "try again", preferredStyle: .alert)
        logInAlert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        self.present(logInAlert, animated: true, completion: nil)

    }
    let registerSuccess = self.storyboard?.instantiateViewController(withIdentifier: "SignInVC")
    self.present(registerSuccess!, animated: true, completion: nil)
}

}

这是我在数据库中的结构的图像

如果有人能解释为什么它们按字母顺序显示,那就太好了。

【问题讨论】:

  • 这很可能与您的查询有关,但请发布您的数据库结构以便我确认。我们需要知道您是如何存储帖子的
  • @DoesData 我现在已经编辑了这个问题,我也会从我的数据库在 firebase 中的样子得到一张图片
  • 我需要查看数据库结构。您只需要上传上传代码。
  • @DoesData 抱歉花了一些时间,但现在我得到了照片,我已经解释了我上传它们的顺序以及它们在应用程序中的显示方式

标签: ios uitableview firebase firebase-realtime-database swift4


【解决方案1】:

所以我不太确定您希望按什么顺序获取数据,但就像我在评论中所说的那样,问题出在您的查询上。您需要查看toLasttoFirst,您可以这样做here

如果您希望帖子显示在最近上传的位置(从最新到最旧),您可以使用toLasttoFirst 提供相反的功能。查询将如下所示:

func loadData() {
    Database.database().reference().child("posts").queryLimited(toLast: 7).observeSingleEvent(of: .value) { (snapshot) in
        for child in snapshot.children {
            let child = child as? DataSnapshot
            self.posts.add(child.value)
            self.postsTableView.reloadData()
        }
    }
}

func loadData() {
    Database.database().reference().child("posts").queryLimited(toFirst: 7).observeSingleEvent(of: .value) { (snapshot) in
        for child in snapshot.children {
            let child = child as? DataSnapshot
            self.posts.add(child.value)
            self.postsTableView.reloadData()
        }
    }
}

如果您在应用中使用此功能,您将需要分页。您可以在 Firebase herehere 上找到一些关于分页的好博文。

如果您想检索所有帖子(不太可能),那么您可以使用 startAtendAt source,但您需要知道开始或结束的键。

Firebase 不保证按顺序返回信息。这就是为什么您需要正确查询并循环以正确顺序返回的快照,以保持您的帖子按时间排序。

您还可以为每个帖子添加时间戳look at this question for help。然后按时间戳对数据数组进行排序。但是,我认为正确查询更有意义。

【讨论】:

  • 嗯,我会试着看看我能在这里做什么,我对 swift 和 firebase 很陌生,我只想做到这一点,所以最近上传的 post 首先显示在表格视图 @DoesData
  • 就像我说的那样,使用 toLast 可以获取您最近的帖子。如果您希望用户能够滚动或较旧的帖子或加载的不仅仅是最初加载的帖子,您将需要分页。例如,如果您使用 toLast: 20 那么它只会加载 20 个最近的帖子而不是其他任何内容。
  • 时间戳听起来是个好主意,直​​到我学会正确查询事物,因为现在我很难理解哈哈,但我非常感谢你的帮助,我会尝试时间戳和修复查询我同意修复查询我是最好的选择
  • 我可以像toLast: 1000 一样使用吗?不完全是 1000,但我的意思是很多
  • 如果没问题,我想添加您提供的第一个示例。我在哪里实施分页?它只是一个功能还是我如何使用它?因为这是我第一次听到这个词呵呵@DoesData
猜你喜欢
  • 2021-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-09
相关资源
最近更新 更多