我在firebase中有一些数据,我试图按时间戳组织。我已将此代码合并到cellForRowAt
中func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let seconds = post["pub_time"] as? Double {
let timeStampDate = NSDate(timeIntervalSince1970: seconds/1000)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let formating = timeStampDate as Date
let timeAgo = timeAgoSinceDate(formating)
cell.Time.text = timeAgo
posts.sort(by: { $0.timeStampDate.compare($1.timeStampDate) == .orderedAscending })
}
但在posts.sort(by: { $0.timeStampDate.compare($1.timeStampDate) == .orderedAscending })
我一直收到错误表达式类型bool是不明确的,没有更多上下文,我不确定我做错了什么
这或多或少是我的视图控制器的样子
var posts = NSMutableArray()
func loadData(){
Database.database().reference().child("main").child("posts").queryOrdered(byChild: "pub_time").observeSingleEvent(of: .value, with: { snapshot in
if let postsDictionary = snapshot .value as? [String: AnyObject] {
for post in postsDictionary {
posts.add(post.value)
}
self.TableView.reloadData()
}
})
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Configure the cell...
let cell = tableView.dequeueReusableCell(withIdentifier: "Cells", for: indexPath) as! FeedTableViewCell
//Configure the cell
let post = posts[indexPath.row] as! [String: AnyObject]
cell.Title.text = post["title"] as? String
if let seconds = post["pub_time"] as? Double {
let timeStampDate = NSDate(timeIntervalSince1970: seconds/1000)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let formating = timeStampDate as Date
let timeAgo = timeAgoSinceDate(formating)
cell.Time.text = timeAgo
}
return cell
}
答案 0 :(得分:1)
这里是如何对一组对象进行排序的; acending是默认顺序。
假设您有像这样的PostClass
class PostClass {
var timeStampDate = "" //assume the timestamps are yyyyMMddhhmmss strings
var post = ""
}
并将它们存储在posts数组中
var posts = [PostClass]()
对数组中的posts对象进行排序的代码是:
posts.sort(by: {$0.timeStampDate < $1.timeStampDate })
话虽如此,您可能需要考虑让Firebase执行繁重的工作并为您订购数据,以便以正确的顺序在快照中显示。
假设您有Firebase结构
posts
post_0
post: "A post about some stuff"
timestamp: "2"
post_1
post: "Posting about how to post"
timestamp: "3"
post_2
post: "The post for you"
timestamp: "1"
我们要加载帖子,按时间戳排序
let postsRef = self.ref.child("posts")
let postQuery = postsRef.queryOrdered(byChild: "timestamp")
postQuery.observeSingleEvent(of: .value, with: { snapshot in
for child in snapshot.children {
let snap = child as! DataSnapshot
let dict = snap.value as! [String: Any]
let post = dict["post"] as! String
let ts = dict["timestamp"] as! Int
print(ts, post)
}
})
和输出
1 The post for you
2 Posting about how to post
3 A post about some stuff
对于这个例子,我使用1,2,3作为我的时间戳,但yyyyMMddhhmmss(20180618101000)格式也可以使用,并提供人类可读的正确排序。