gpt4 book ai didi

ios - 连接到Firebase时如何在重启后保存tableView分离

转载 作者:可可西里 更新时间:2023-11-01 01:55:31 25 4
gpt4 key购买 nike

我是编程新手,目前正在尝试使用 firebase。我正在构建一个类似应用程序的新闻源,它在我的 tableView 中显示自定义类型的单元格。我目前遇到的问题是,在应用程序重新启动后,分离就像 firebase 中的分离。但我希望最新的排在第一位并留在那里。我考虑过将数组保存在核心数据中,但我不太喜欢这个选项。所以我的问题是:如何将帖子从最新到最旧排序?

var ref: DatabaseReference!

var posts = [String]()
var timeRef = [String]()
var userRef = [String]()

override func viewDidLoad() {
super.viewDidLoad()
addSlideMenuButton()

ref = Database.database().reference()

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

let newPost = snapshot.value as? NSDictionary
let post_title:String = newPost!["post_title"] as? String ?? "error"

let newPostTime = snapshot.value as? NSDictionary
let post_time:String = newPostTime!["post_time"] as? String ?? "error"

let newPostUser = snapshot.value as? NSDictionary
let post_user:String = newPostUser!["post_user"] as? String ?? "Team"

self.posts.insert(post_title, at: 0)
self.timeRef.insert(post_time, at: 0)
self.userRef.insert(post_user, at: 0)

self.newsfeedTableView.reloadData()
})
}

(如果您需要更多代码,请告诉我)

最佳答案

我不熟悉 firebase,但它可能内置了一些可以帮助您完成该任务的东西,因为它很常见。

无论如何,这就是你可以用你的方法做到这一点的方式:

let isoFormatter = ISO8601DateFormatter()

// dateStrings will be fetched from your database
let dateStrings = [
"2018-12-07T09:21:42Z",
"2018-12-07T09:19:42Z",
"2018-12-07T09:20:42Z"
]

// here we're converting the strings to an actual Date types
let dates = dateStrings.compactMap { isoFormatter.date(from: $0) }

// sorting in descending order
let sortedDates = dates.sorted { $0 > $1 }

print(sortedDates)
/*
prints-

[
2018-12-07 09:21:42 +0000,
2018-12-07 09:20:42 +0000,
2018-12-07 09:19:42 +0000
]
*/

您可以使用 isoFormatter.string(from: Date) 将日期上传到您的数据库

关于ios - 连接到Firebase时如何在重启后保存tableView分离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53664508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com