gpt4 book ai didi

ios - QueryEndingAtValue 函数在 Swift firebase 中无法正常工作

转载 作者:行者123 更新时间:2023-11-28 11:58:41 25 4
gpt4 key购买 nike

我一直在实现代码,使分页滚动能够通过从 firebase 数据库中获取一定数量的数据来获取数据。

首先,然后错误说

Terminating app due to uncaught exception 'InvalidQueryParameter', reason: 'Can't use queryEndingAtValue: with other types than string in combination with queryOrderedByKey'

下面是产生上述错误的实际代码

static func fetchPostsWith(last_key: String?, completion: @escaping (([PostModel]?) -> Void)) {

var posts = [PostModel]()
let count = 2

let ref = Database.database().reference().child(PATH.all_posts)
let this_key = UInt(count + 1)
let that_key = UInt(count)

let this = ref.queryOrderedByKey().queryEnding(atValue: last_key).queryLimited(toLast: this_key)
let that = ref.queryOrderedByKey().queryLimited(toLast: that_key)

let query = (last_key != nil) ? this : that

query.observeSingleEvent(of: .value) { (snapshot) in
if snapshot.exists() {
for snap in snapshot.children {
if let d = snap as? DataSnapshot {
let post = PostModel(snapshot: d)
print(post.key ?? "")
posts.append(post)
}
}
posts.sort { $0.date! > $1.date! }
posts = Array(posts.dropFirst())
completion(posts)
} else {
completion(nil)
}
}
}

它试图做的是获取一个路径,其中所有帖子都按自动 ID 存储。但是错误不断出现,所以我不知道出了什么问题。你有什么想法吗?

 func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// index is the last and last fetched then
print(self.feeds.count - 1 == indexPath.row, "index ", self.hasFetchedLastPage, "has fetched last")
if self.feeds.count - 1 == indexPath.row {
let lastKey = self.feeds[indexPath.row].key
if lastKey != self.previousKey {
self.getFeeds(lastKey: lastKey)
} else {
self.previousKey = lastKey ?? ""
}
}
print("Cell Display Number", indexPath.row)
}

func getFeeds(lastKey: String?) {
print(self.isFetching, "is fetching")
guard !self.isFetching else {
self.previousKey = ""
return
}
self.isFetching = true
print(self.isFetching, "is fetching")
FirebaseModel.fetchPostsWith(last_key: lastKey) { ( d ) in
self.isFetching = false
if let data = d {
if self.feeds.isEmpty { //It'd be, when it's the first time.
self.feeds.append(contentsOf: data)
self.tableView.reloadData()
print("Initial Load", lastKey ?? "no key")
} else {
self.hasFetchedLastPage = self.feeds.count < 2
self.feeds.append(contentsOf: data)
self.tableView.reloadData()
print("Reloaded", lastKey ?? "no key")
}
}
}
}

我想实现一个支持分页的 tableView。如果您能帮助此代码正常工作,我们将不胜感激。

最佳答案

您正在将 last_key 转换为数字,而键始终是字符串。错误消息告诉您这两种类型不兼容。这意味着您必须在代码中将数字转换回字符串,然后再将其传递给查询:

let this = ref.queryOrderedByKey().queryEnding(atValue: last_key).queryLimited(toLast: String(this_key))
let that = ref.queryOrderedByKey().queryLimited(toLast: String(that_key))

关于ios - QueryEndingAtValue 函数在 Swift firebase 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50424732/

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