簡體   English   中英

Firebase僅加載一次數據並使用完成處理程序關閉

[英]Firebase only load data once and close using completion handler

我決定將Firebase用作我正在制作的應用程序的后端。 我意識到的一件事是,一旦填充了用於表視圖的數據,Firebase的網絡連接就不會關閉。

有沒有一種方法可以關閉連接,以免耗盡用戶的數據? 在獲取數據的代碼中,我將其存儲在本地,因此它仍然存在。

    class HomeTableViewController: UITableViewController{

    //firebase refrences
    var restaurantArray = [Restaurant]()

    var dataBaseRef: FIRDatabaseReference! {
        return FIRDatabase.database().reference()
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Home"
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "menuIcon"), style: .plain, target: self, action: #selector(SSASideMenu.presentLeftMenuViewController))
        navigationItem.leftBarButtonItem?.setBackButtonBackgroundImage(#imageLiteral(resourceName: "backButton"), for: .normal , barMetrics: .default)

        tableView.backgroundView = UIImageView(image: UIImage(named: "Background"))
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        fetchRestaurants()
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    func fetchRestaurants(){
       dataBaseRef.child("AthensRestaurants/Restaurants").observe(.value, with: { (snapshot) in
            var results = [Restaurant]()

            for res in snapshot.children{
                let res = Restaurant(snapshot: res as! FIRDataSnapshot)
                results.append(res)
            }

            self.restaurantArray = results.sorted(by: { (u1, u2) -> Bool in
                u1.name < u2.name
            })
            self.tableView.reloadData()
            self.dataBaseRef.removeAllObservers()
    }) { (error) in
    print(error.localizedDescription)
    }
}
      // MARK: - Table view data source
      // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return restaurantArray.count
    }


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

        // Configure the cell...

        cell.configureCell(res: restaurantArray[indexPath.row])
        cell.backgroundColor = UIColor.clear
        cell.contentView.layer.borderColor = UIColor.clear.cgColor
        cell.contentView.layer.borderWidth = 1.5
        return cell
    }

    //transfers data to new page
    func showRestaurantViewControllerWith(_ res: Restaurant) {
        let storyBoard = UIStoryboard(name: "Main", bundle: nil)
        let destinationVC = storyBoard.instantiateViewController(withIdentifier: "RestaurantDetails") as! RestaurantDetailViewController
        destinationVC.resTransfer = res
        self.navigationController?.pushViewController(destinationVC, animated: true)
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.showRestaurantViewControllerWith(self.restaurantArray[indexPath.row])
    }











}

你打電話時:

dataBaseRef.child("AthensRestaurants/Restaurants").observe(.value

您開始觀察數據庫中Restaurants節點的值。 您的代碼塊將立即使用當前值運行,然后只要該值更改就運行 因此,Firebase數據庫客戶端將保持與服務器的開放連接。

如果不需要更新的值,則可以向以下人員注冊觀察者:

dataBaseRef.child("AthensRestaurants/Restaurants"). observeSingleEvent(of: .value

請參閱Firebase文檔中的讀取數據一次

這樣可以確保您僅獲得初始值,而不必等待更新。 但是關閉連接可能仍需要很長時間。

要自己顯式管理連接的打開/關閉,可以調用goOffline() / goOnline() 有關goOffline()信息,請參閱Firebase參考文檔

我認為您應該使用以下方法,以便僅加載一次數據:

dataBaseRef.child("AthensRestaurants/Restaurants").observeSingleEvent(of: .value, with: { (snapshot) in
 var results = [Restaurant]()

        for res in snapshot.children{
            let res = Restaurant(snapshot: res as! FIRDataSnapshot)
            results.append(res)
        }

        self.restaurantArray = results.sorted(by: { (u1, u2) -> Bool in
            u1.name < u2.name
        })
        self.tableView.reloadData()
        self.dataBaseRef.removeAllObservers()
  }) { (error) in
    print(error.localizedDescription)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM