swift - 从 Firebase 下载数据到 Xcode UITableView

标签 swift firebase uitableview firebase-realtime-database

大家好,我正在尝试从我的 Firebase 数据库下载特定元素(事件、标题以及纬度和经度)。在拍摄数据快照并尝试选择单个元素标题时,出现错误,提示已找到 nil。

这是JSON结构

{
  "location" : {
   "-LY55OLlInZ0HLepGZWp" : {
      "Activity" : "Legs",
      "Description" : "Anainssnsj skak\nHsians\nAhah",
      "Difficulty" : "Beginner",
      "Lat" : "",
      "Long" : "",
      "Rating" : "3",
      "Title" : "Busan",
      "id" : "-LY55OLjAA3Cbcvaf8SG"
    },
    "-LY55SN53euLPN9UxoM5" : {
      "Activity" : "Board",
      "Description" : "Stktwks",
      "Difficulty" : "Beginner",
      "Lat" : "lat:-35.14202623881991",
      "Long" : "long:138.54526039212942",
      "Rating" : "3",
      "Title" : "Jettei",
      "id" : "-LY55SN40TARVvysV8fi"
    },
  },

这是将信息保存到 Firebase 中的代码:

  func saveLocationInformation() {
    let key = refLocation.childByAutoId().key

    guard let title = locationTitle.text  else {return}
    guard let location = geoCoordinate.text  else {return}
    guard let long = geoLong.text else {return}
    guard let description = descriptionText.text  else {return}
    guard let rating = flameNumber.text  else {return}
    guard let difficulty = difficultyRating.text else {return}
    guard let activity = activityLabel.text else {return}


    let lTitle = [
        "id": key,
        "Title": title,
        "Activity": activity,
        "Lat": location,
        "Long": long,
        "Description": description,
        "Rating": rating,
        "Difficulty": difficulty,
    ] as [String:Any]
    let lID = [
        "id": key,
    ] as [String:Any]

    refLocation.childByAutoId().setValue(lTitle)

}

下面是尝试获取数据快照并将信息放入 TableView 的代码

import UIKit
import Firebase
class TableViewControllerVC: UITableViewController {


 var locationData = [locationSearch]()

 var ref: DatabaseReference!
 var dataHandle: DatabaseHandle?




 override func viewDidLoad() {

     super.viewDidLoad()

     loadInfo()
 }

 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return locationData.count
 }



 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "TabViewCell", for: indexPath)



    return cell
}


 func loadInfo() {
    ref = Database.database().reference()
    ref.child("location").observe(.value) { (snapshot: DataSnapshot) in
        if let dict = snapshot.value as? [String: AnyObject] {
            //
            let titleT =  dict["Title"]
            //                let activityA = dict["Activity"] as! String
            //                let loc = locationSearch(titleText: titleT, activityText: activityA)
            //                self.locationData.append(loc)

            print(titleT)
            self.tableView.reloadData()
        }
    }

}




}

最佳答案

现在您的观察者正在选择子 ID 作为值,而不是他们的字典

如果你想设置一个观察者来寻找所有 child 并监听 child 添加“location”分支,尝试替换loadInfo() 与此:

func loadInfo() {
    ref = Database.database().reference()

    ref.child("location").observe(.childAdded) { (snapshot: DataSnapshot) in
        // will iterate through each child of "location" branch
        if let dict = snapshot.value as? [String: AnyObject] {
            let titleT =  dict["Title"] as? String

            print(titleT) // will return "Title" branch value
        }
    }

}

或者,如果您希望像原始代码那样使用值快照,请像这样使用此单一事件观察来获取子项列表并遍历它们:

func loadInfoOnce() {
    ref = Database.database().reference()

    ref.child("location").observeSingleEvent(of: .value) { (snapshot) in
        // will iterate through each child of "location" branch
        if let locationIds = snapshot.children.allObjects as? [DataSnapshot] {

            for locationId in locationIds {
                let dict = locationId.value as? [String: AnyObject]
                let titleT =  dict["Title"] as? String
                print(titleT) // will return "Title" value for each location id
            }
        }
    }

}

关于swift - 从 Firebase 下载数据到 Xcode UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54756965/

相关文章:

iphone - iOS - 如何处理自定义表格单元格中的方向变化

ios - 带有 tableview 的 popover Controller 在 swift 中

iOS 在后台或应用程序激活时执行预定操作

ios - 在 Swift 中将静态方法设置为 UITapGestureRecognizer 的 Action

firebase - 缺少必要的权限 resourcemanager.projects.getIamPolicy

ios - 管理两个单元格之间的交换而不是更改其他 UITableViewcells 的 NSIndexpath

ios - Swift:变量获取以错误顺序分配的值

swift - 如何使用 Swift 移位位?

javascript - Firestore 云功能无法在本地运行

firebase - 如何撤消 Firestore 中的更改?