Populating UITableViewController With Firebase Data Swift, Xcode 7

前端 未结 2 875
梦谈多话
梦谈多话 2020-12-29 17:18

I am working with swift in Xcode 7. I am totally new to Swift, Xcode, and Firebase. I would like to have three UITableViewContro

2条回答
  •  不思量自难忘°
    2020-12-29 17:55

    This question is broad, in that it asks how to do three different tasks.

    I think you'll be better off getting answers if you only ask for one thing at a time.

    I can help you with populating a UITableViewController with Firebase.

    class MyTableViewController: UITableViewController {
      // your firebase reference as a property
      var ref: Firebase! 
      // your data source, you can replace this with your own model if you wish
      var items = [FDataSnapshot]() 
    
      override func viewDidLoad() {
        super.viewDidLoad()
        // initialize the ref in viewDidLoad
        ref = Firebase(url: "/items")
      }
    
      override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // listen for update with the .Value event
        ref.observeEventType(.Value) { (snapshot: FDataSnapshot!) in
    
          var newItems = [FDataSnapshot]()
    
          // loop through the children and append them to the new array
          for item in snapshot.children {
            newItems.append(item as! FDataSnapshot)
          }
    
          // replace the old array
          self.items = newItems
          // reload the UITableView
          self.tableView.reloadData()
        }
      } 
    }
    

    This technique uses the .Value event, you can also use .ChildAdded, but then you have to keep track of .ChildChanged, '.ChildRemoved', and .ChildMoved, which can get pretty complicated.

    The FirebaseUI library for iOS handles this pretty easily.

    dataSource = FirebaseTableViewDataSource(ref: self.firebaseRef, cellReuseIdentifier: "", view: self.tableView)
    
    dataSource.populateCellWithBlock { (cell: UITableViewCell, obj: NSObject) -> Void in
      let snap = obj as! FDataSnapshot
    
      // Populate cell as you see fit, like as below
      cell.textLabel?.text = snap.key as String
    }
    

提交回复
热议问题