【问题标题】:Posts Being Uploaded Randomly in Collection View - Swift & Firebase在收藏视图中随机上传的帖子 - Swift 和 Firebase
【发布时间】:2025-12-19 19:50:11
【问题描述】:

我一直在重构我的代码,但现在我在处理这些帖子时遇到了问题。

每当我将新帖子添加到收藏视图时,它都会添加到随机单元格中且无序,而不是添加到第一个帖子中。

我知道 原因是 fetchuser 函数,并且由于异步加载而被告知,但不知道该怎么做才能纠正此问题。

有人可以帮我弄清楚该怎么做才能将我的帖子添加到第一个单元格中吗?

 @objc func observePostsAdoption() {
    let postsRef = Database.database().reference().child("posts")
    postsRef.queryOrdered(byChild: "postType").queryEqual(toValue: "adopt").observe(.value) { (snapshot) in
        var tempPost = [Posts]()
        for child in snapshot.children {
            if let childSnapshot = child as? DataSnapshot {
                let dict = childSnapshot.value as? [String: Any]
                let newAdoptiondPost = Posts.transformPost(dict: dict!)
                //This will look up all users at once
                self.fetchUser(userid: newAdoptiondPost.userid!, completed: {
                 tempPost.insert(newAdoptiondPost, at: 0)
                    DispatchQueue.main.async {
                        self.postsadoption = tempPost
                        self.adoptionCollectionView.reloadData()
                        self.refresherAdoption.endRefreshing()
                    }
            })
            }

        }
    }
}

func fetchUser(userid: String, completed:  @escaping ()-> Void ) {

    Database.database().reference().child("users").child(userid).observeSingleEvent(of: .value) { (snapshot) in
        if let dict = snapshot.value as? [String: Any] {
            let user = UserProfile.transformUser(dict: dict)
            self.users.insert(user, at: 0)
            completed()
        }
    }

}

这是我的帖子结构

class Posts {

//UserView
var uid: String?
var author: UserProfile?
var timestamp: Date?
var userid: String?

func getDateFormattedString() -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "MMM d, HH:mm"
    return formatter.string(from: self.timestamp!)
}

//Image
var photoUrl: URL?

//PostInformation View
var city: String?
var municipality: String?
var name: String?
var breed : String?
var phone : String?
var address : String?
var petType: String?
var genderType: String?
var comments: String?

}

扩展帖子{

static func transformPost(dict: [String: Any]) -> Posts {

    let post = Posts()

    //Post Picture
    let photoUrl = dict["photoUrl"] as? String
    post.photoUrl = URL(string: photoUrl!)

    //INFO POSTS
    post.userid = dict["userid"] as? String
    post.city = dict["city"] as? String
    post.municipality = dict["municipality"] as? String
    post.name = dict["name"] as? String
    post.breed = dict["breed"] as? String
    post.phone = dict["phone"] as? String
    post.address = dict["address"] as? String
    post.comments = dict["comments"] as? String
    post.petType = dict["petType"] as? String
    post.genderType = dict["gender"] as? String
    let timestamp = dict["timestamp"] as? Double
    post.timestamp = Date(timeIntervalSince1970: timestamp!/1000)

    return post

}

}

【问题讨论】:

  • 如果您的 Post 对象具有时间戳等属性,那么进行排序将非常容易。你能展示你的 Posts 结构吗?
  • 嘿加洛!我已将其添加到问题中。
  • 另外,在这种情况下,我需要按“postType”排序,因为我还有其他几个 postType,例如 lost and found。我可以按两种不同的类型排序吗?时间戳和 postType?
  • postType 到底是什么意思?我没有看到设置了 postType 的任何属性。
  • 签入第一个函数。观察帖子采用。 postType 在 Firebase --> let postsRef = Database.database().reference().child("posts") postsRef.queryOrdered(byChild: "postType").queryEqual(toValue: "adopt").observe(.值)

标签: swift firebase asynchronous uicollectionview uicollectionviewcell


【解决方案1】:

如果您已经拥有按帖子类型排序的帖子,则可以根据时间戳进行排序。例如

@objc func observePostsAdoption() {
        let postsRef = Database.database().reference().child("posts")
        postsRef.queryOrdered(byChild: "postType").queryEqual(toValue: "adopt").observe(.value) { (snapshot) in
            var tempPost = [Posts]()
            for child in snapshot.children {
                if let childSnapshot = child as? DataSnapshot {
                    let dict = childSnapshot.value as? [String: Any]
                    let newAdoptiondPost = Posts.transformPost(dict: dict!)
                    //This will look up all users at once
                    self.fetchUser(userid: newAdoptiondPost.userid!, completed: {
                        tempPost.insert(newAdoptiondPost, at: 0)
                        DispatchQueue.main.async {
                            self.postsadoption = tempPost
                            self.postsadoption.sort { (p1, p2) -> Bool in
                                return p1.timeStamp?.compare(p2.timeStamp!) == .orderdDescending
                            }
                            self.adoptionCollectionView.reloadData()
                            self.refresherAdoption.endRefreshing()
                        }
                    })
                }

            }
        }
    }

这样,帖子采用数组将根据您拥有的时间戳进行排序。

【讨论】:

    最近更新 更多