Swift - 从Firebase获取数据并将其存储到数组中

时间:2016-12-06 16:11:37

标签: ios swift firebase firebase-realtime-database tableview

我正在尝试从Firebase数据库中获取一个条形列表并将其存储在一个数组中,以便我可以在表格视图中显示它。

我已经配置了Firebase并设法将应用程序中的数据作为String,AnyObject字典获取。

这是我的代码:

struct Bar {

    var latitude: Double?
    var longitude: Double?
    var name: String!
    var phoneNumber: String?
    var happyHour: String?
    var url: NSURL?
    var barLogo: UIImage?
    var followers: Int?
    var addedToFavorites: Int?
    var zipCode: Double?
    var area: String?

}


class ViewController: UIViewController {

    var ref: FIRDatabaseReference!
    var refHandle: UInt!

override func viewDidLoad() {
        super.viewDidLoad()

        ref = FIRDatabase.database().reference()
        refHandle = ref.observe(FIRDataEventType.value , with: {(snapshot) in
            let dataDict = snapshot.value as! [String : AnyObject]



        }
        )
 }

以下是我从Firebase导出的JSON:

{
  "data" : {
    "bars" : {
      "bar1" : {
        "addedToFavorites" : 0,
        "area" : "upper east",
        "follwers" : 0,
        "happyHour" : "m-f 16-19",
        "lattitude" : 4412334,
        "longitude" : 223455,
        "name" : "bar1",
        "phone" : 212222,
        "url" : "http://www.bar1.com",
        "zipCode" : 12345
      },
      "bar2" : {
        "addedToFavorites" : 0,
        "area" : "upper west",
        "follwers" : 0,
        "happyHour" : "f - s 20-22",
        "lattitude" : 4443221,
        "longitude" : 221234,
        "name" : "bar 2",
        "phone" : 215555,
        "url" : "http://www.bar2.com",
        "zipCode" : 54321
      }
    }
  }
}

最好的办法是什么?

我想缩放它并下载数百个条形图,因此手动从字典中获取数据并将其存储到Bar结构变量中然后将其附加到数组并不是我想要继续的路径。

我需要一个解决方案来抓取所有条形图并以某种方式将它们添加到数组(或任何其他方法将它们显示到tableView中)。

提前致谢。

1 个答案:

答案 0 :(得分:0)

我找到了解决此问题的方法:

首先,我摆脱了结构并创建了一个类:

我的班级档案:

import Foundation  
import UIKit

    class Bar {

        private var _name: String!
        private var _area: String!
        private var _latitude: Double!
        private var _longitude: Double!
        private var _followers: Int!
        private var _happyHour: String!
        private var _phone: Double!
        private var _url: String!
        private var _zipCode: Double!
        private var _addedToFav: Int!

        var name: String! {
            return _name
        }

        var area: String! {
            return _area
        }

        var latitude: Double! {
            return _latitude
        }

        var longitude: Double! {
            return _longitude
        }

        var followers: Int! {
            return _followers
        }

        var happyHour: String! {
            return _happyHour
        }

        var phone: Double! {
            return _phone
        }

        var url: String! {
            return _url
        }

        var zipCode: Double! {
            return _zipCode
        }

        var addedToFav: Int! {
            return _addedToFav
        }



        init(name: String,area: String! , latitude: Double, longitude: Double, followers: Int, happyHour: String, phone: Double, url: String, zipCode: Double, addedToFav: Int) {
            self._name = name
            self._area = area
            self._latitude = latitude
            self._longitude = longitude
            self._followers = followers
            self._happyHour = happyHour
            self._phone = phone
            self._url = url
            self._zipCode = zipCode
            self._addedToFav = addedToFav
        }

        init(barData: Dictionary<String, AnyObject>) {


            if let name = barData["name"] as? String {
                 self._name = name
            }

            if let area = barData["area"] as? String {
                self._area = area 
            }

            if let latitude = barData["lattitude"] as? Double {
                self._latitude = latitude
            }

            if let longitude = barData["longitude"] as? Double {
                self._longitude = longitude
            }

            if let followers = barData["followers"] as? Int {
                self._followers = followers
            }

            if let happyHour = barData["happyHour"] as? String {
                self._happyHour = happyHour
            }

            if let phone = barData["phone"] as? Double {
                self._phone = phone
            }

            if let url = barData["url"] as? String {
                self._url = url
            }

            if let zipCode = barData["zipCode"] as? Double {
                self._zipCode = zipCode
            }

            if let addedToFav = barData["addedToFavorites"] as? Int {
                self._addedToFav = addedToFav
            }
        }


    }

我创建了一个带有单例

的DataService类

数据服务类文件:

import Foundation
import Firebase

let URL_BASE = FIRDatabase.database().reference()

class DataService {

    static let ds = DataService()

    private var _REF_BASE = URL_BASE
    private var _REF_BARS = URL_BASE.child("data").child("bars")



    var REF_BASE: FIRDatabaseReference {
        return REF_BASE
    }

    var REF_BARS: FIRDatabaseReference {
        return _REF_BARS
    }
}

我修改过的viewController文件(我没有使用tableViewController)

class ViewController: UIViewController ,  UITableViewDelegate , UITableViewDataSource {

    @IBOutlet weak var myTableView: UITableView!

    var baruri = [Bar]()



    override func viewDidLoad() {

        super.viewDidLoad()
        myTableView.dataSource = self
        myTableView.delegate = self


        DataService.ds.REF_BARS.observe(.value, with: { (snapshot) in

            if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
                for snap in snapshot {
                    print(snap)
                    if let barData = snap.value as? Dictionary<String, AnyObject> {
                        let bar = Bar(barData: barData)
                        self.baruri.append(bar)
                        print(self.baruri)
                        self.myTableView.reloadData()
                    }
                   self.myTableView.reloadData()
                }
               self.myTableView.reloadData()
            }
            self.myTableView.reloadData()
        }


        )

    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    func tableView( _ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.myTableView.dequeueReusableCell(withIdentifier: "newCell", for: indexPath) as! NewCell

        var baruriTabel: Bar!

        baruriTabel = baruri[indexPath.row]

        cell.barNameLBl.text = baruriTabel.name
        cell.followersNrLbl.text = String(baruriTabel.followers)
        cell.areaLbl.text = baruriTabel.area
        cell.addedToFavoritesLbl.text = String(baruriTabel.addedToFav)
        cell.happyHourLbl.text = baruriTabel.happyHour
        cell.urlLbl.text = baruriTabel.url
        cell.lattitudeLbl.text = String(baruriTabel.latitude)
        cell.longitudeLbl.text = String(baruriTabel.longitude)
        cell.phoneLbl.text = String(baruriTabel.phone)
        cell.zipCode.text = String(baruriTabel.zipCode)

        return cell
    }


}