我的问题与此处几乎相同:Firebase get child ID swift ios与此问题Retrieve randomly generated child ID from Firebase略有不同。
我有一个UITableViewController,用户可以在其中创建自己的频道。每个人都可以查看这些频道,每个人都可以点按其中一个频道,然后进入新视图。现在,当用户点击任何这些单元格时,我想获得当前的频道ID,用户只是点击了。
现在我的问题是:如何获得当前ID(-KDD6 [...] Q0Q)?问题2的答案将为房间的创建者提供技巧,但由于他们没有创建密钥,因此不能被其他用户使用。可以使用问题1的答案,但截至目前,它只是遍历每个随机密钥。但是我需要与用户当前所在频道相关的密钥。下面是一些代码,用于说明我现在如何制作频道。提前致谢。编辑:这是我的所有代码。我现在在didSelectRow函数中得到一个错误“类型[Channel]的值没有成员'name'。
import UIKit
import Firebase
import Foundation
enum Section: Int {
case createNewChannelSection = 0
case currentChannelsSection
}
extension multiplayerChannelView: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
filterContentForSearchText(searchText: searchController.searchBar.text!)
}
}
class multiplayerChannelView: UITableViewController {
// MARK: Properties
var channels: [Channel] = []
let searchController = UISearchController(searchResultsController: nil)
var filteredChannels = [Channel]()
private lazy var channelRef: FIRDatabaseReference = FIRDatabase.database().reference().child("channels")
private var channelRefHandle: FIRDatabaseHandle?
var senderDisplayName: String?
var newChannelTextField: UITextField?
override func viewDidLoad() {
super.viewDidLoad()
title = "Rooms"
observeChannels()
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar
}
deinit {
if let refHandle = channelRefHandle {
channelRef.removeObserver(withHandle: refHandle)
}
}
func filterContentForSearchText(searchText: String, scope: String = "All") {
filteredChannels = channels.filter { Channel in
return (Channel.name.lowercased().range(of: searchText.lowercased()) != nil)
}
tableView.reloadData()
}
@IBAction func createChannel(_ sender: AnyObject) {
if let name = newChannelTextField?.text {
let newChannelRef = channelRef.childByAutoId()
let channelItem = [ // 3
"name": name
]
newChannelRef.setValue(channelItem)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
private func observeChannels() {
channelRefHandle = channelRef.observe(.childAdded, with: { (snapshot) -> Void in // 1
let channelData = snapshot.value as! Dictionary<String, AnyObject> // 2
let id = snapshot.key
if let name = channelData["name"] as! String!, name.characters.count > 0 { // 3
self.channels.append(Channel(id: id, name: name))
self.tableView.reloadData()
} else {
print("Error! Could not decode channel data")
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let currentSection: Section = Section(rawValue: section) {
switch currentSection {
case .createNewChannelSection:
return 1
case .currentChannelsSection:
if searchController.isActive && searchController.searchBar.text != "" {
return filteredChannels.count
}
else{
return channels.count
}
}
} else {
return 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let reuseIdentifier = (indexPath as NSIndexPath).section == Section.createNewChannelSection.rawValue ? "NewChannel" : "ExistingChannel"
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
if (indexPath as NSIndexPath).section == Section.createNewChannelSection.rawValue {
if let createNewChannelCell = cell as? CreateChannelCell {
newChannelTextField = createNewChannelCell.newChannelNameField
}
} else if (indexPath as NSIndexPath).section == Section.currentChannelsSection.rawValue {
if searchController.isActive && searchController.searchBar.text != "" {
cell.textLabel?.text = filteredChannels[(indexPath as NSIndexPath).row].name
} else {
cell.textLabel?.text = channels[(indexPath as NSIndexPath).row].name
}
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == Section.currentChannelsSection.rawValue {
var channel = channels
if searchController.isActive && searchController.searchBar.text != "" {
channel = [filteredChannels[(indexPath as NSIndexPath).row]]
channelRef.queryOrdered(byChild: "name").queryEqual(toValue: channel.name).observe(.childAdded, with: {snapshot in
let currentID = snapshot.key
print(currentID)
})
}
else
{
channel = [channels[(indexPath as NSIndexPath).row]]
channelRef.queryOrdered(byChild: "name").queryEqual(toValue: channel.name).observe(.childAdded, with: {snapshot in
let currentID = snapshot.key
print(currentID)
})
}
self.performSegue(withIdentifier: "ShowChannel", sender: channel)
}
}
}
internal class Channel {
internal let id: String
internal let name: String
init(id: String, name: String) {
self.id = id
self.name = name
}
}
编辑2:我读到了关于segue的准备,但是这不能正确执行:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if let channel = sender as? Channel {
let chatVc = segue.destination as! channelMultiplayerViewController
chatVc.channel = channel
chatVc.channelRef = channelRef.child(channel.id)
}
}
执行segue函数的准备,但if let channel = sender为?频道不是,因为它是零。
答案 0 :(得分:1)
您必须查询firebase以获取密钥。您当前设置的唯一问题是您希望防止重复的名称。这样做的原因是,如果您没有在应用程序中存储每个频道的所有密钥并且必须查询密钥,则查询确切密钥的唯一方法是单个节点&#34; name&#34;。如果存在重复的名称,那么我添加到你的did select行方法的代码中的childAdded将返回两个,并且没有其他数据可以帮助识别它。
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == Section.currentChannelsSection.rawValue {
var channel = channels
if searchController.isActive && searchController.searchBar.text != "" {
channel = [filteredChannels[(indexPath as NSIndexPath).row]]
channelRef.queryOrdered(byChild: "name").queryEqual(toValue: channel.name).observe(.childAdded, with: {snapshot in
let currentID = snapshot.key
})
}
else
{
channel = [channels[(indexPath as NSIndexPath).row]]
channelRef.queryOrdered(byChild: "name").queryEqual(toValue: channel.name).observe(.childAdded, with: {snapshot in
let currentID = snapshot.key
})
}
self.performSegue(withIdentifier: "ShowChannel", sender: channel)
}
}
我建议您在查看加载时获取所有频道的数据:
override func viewDidLoad(){
channelRef.observe(.childAdded, with: {snapshot in
let data = snapshot.value as? [String:Any] ?? [:]
let key = snapshot.key
let name = data["name"]
let chnl = Channel.init(id:key, name:name)
self.channels.append(chnl)
self.tableView.reloadData()
})
}
当你使用.childAdded时,一个监听器将对这个VC是活动的,所以当你创建一个新的通道时,这个代码将被调用并重新加载你的表。
否则,您可以在创建频道时直接获取密钥:
@IBAction func createChannel(_ sender: AnyObject) {
if let name = newChannelTextField?.text {
let newChannelRef = channelRef.childByAutoId()
let channelItem = [
"name": name
]
newChannelRef.setValue(channelItem)
let channelKey = newChannelRef.key
let newChannel = Channel.init(id:channelKey, name:name)
self.channels.append(newChannel)
self.tableView.reloadData()
}
}
请注意,如果您使用此路线,则没有任何新项目的活动侦听器,这意味着如果其他设备正在添加频道,则其他设备将无法获得更新。最好通过查询从firebase中获取新创建的数据,并在将数据添加到数组时重新加载表。
以下是适用于上述内容的示例Channel类:
import Foundation
// import FirebaseDatabase // import this if you would like to use this class to handle data transactions
class Channel: NSObject {
// change either of these to var if they should be mutable
let id:String
let name:String
// initialize
init (_ id:String, name:String){
self.id = id
self.name = name
}
}
这样您就可以使用模型对象了。如果你不熟悉MVC编码风格,你应该检查一下。它使应用程序更加高效。您可以使用此Channel模型并添加数据检索编码,以便此类处理控制器的数据。这远远超出了你的职位范围。现在这个班应该有效。
上次评论编辑: 在通道选择期间而不是在if块之后,在两个查询块中添加prepareforsegue方法,因为可能在查询完成之前准备segue。有一点需要注意,在我意识到这一点之前,我曾经和你做过同样的事情。是你不必在此时运行查询来获取所选单元格的数据,因为它位于本地数组中。好吧,目前你只是在听更多的孩子。您也可以监听已删除和已更改的子项,以便始终更新本地数据,然后在选择单元格时,您可以直接访问filteredChannels / channels数组,并通过prepareforsegue方法推送通道。我开始这样做了,因为在表格选择期间的查询总是导致奇怪的错误,我必须找到创造性的方法。
childRemoved和childChanged查询可以实现与当前.childAdded方法相同的实现,因为您希望保持侦听器的处理程序在页面deinit上删除它们。但是,如果您不允许删除或更新频道,则可以忽略此操作。