加载数据后如何关闭Firebase连接?

时间:2017-01-16 04:41:37

标签: ios swift firebase firebase-realtime-database

在本课程中,我有一个使用ObserveSingleEvent进入Firebase的方法fetchRestaurants。数据被加载到数组中,并填充表视图单元格。我的问题是,每当我尝试对tableview进行排序时,Firebase连接都不会关闭,甚至会在桌面视图中向上或向下滑动它从Firebase中拉出来并导致接收数据显着增加。你们都推荐什么?过去6小时我一直在我的办公桌前试图关闭我班下面的连接:

//
//  HomeTableViewController.swift
//  Fresco
//
//  Created by Antonio Rodriguez on 12/31/16.
//  Copyright © 2016 FrescoInc. All rights reserved.
//

import UIKit
import Firebase
import FirebaseDatabase

enum selectedScope: Int {
    case name = 0
    case rating = 1
    case price = 2
}


class HomeTableViewController: UITableViewController, UISearchBarDelegate{

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

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

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Home"
        self.searchBarSetup()
        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)
       fetchRestaurants()
        tableView.backgroundView = UIImageView(image: UIImage(named: "mainPageBackground"))
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
       // fetchRestaurants()
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    func fetchRestaurants(){
       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)
    }

}
    // 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])
    }

    func searchBarSetup(){
        let searchBar = UISearchBar()
        searchBar.showsScopeBar = true
        searchBar.scopeButtonTitles = ["Name", "Rating", "Price"]

        searchBar.delegate = self
        self.tableView.tableHeaderView = searchBar
    }
    //Mark: - Search Bar Delegate
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText:String){
        filterTableView(ind: searchBar.selectedScopeButtonIndex)
    }

    func filterTableView(ind: Int){
        switch ind {
        case selectedScope.name.rawValue:
            self.restaurantArray = self.restaurantArray.sorted(by: { (u1, u2) -> Bool in
                u1.name < u2.name
            })
            self.tableView.reloadData()

        case selectedScope.price.rawValue:
            self.restaurantArray = self.restaurantArray.sorted(by: { (u1, u2) -> Bool in
                u1.price.characters.count < u2.price.characters.count
            })
            self.tableView.reloadData()

        case selectedScope.rating.rawValue:
            self.restaurantArray = self.restaurantArray.sorted(by: { (u1, u2) -> Bool in
                u1.rating < u2.rating
            })
            self.tableView.reloadData()
        default:
            print("no type")
        }
    }






}

0 个答案:

没有答案