检索子项的文件夹数据Firebase Swift

时间:2017-08-14 11:52:00

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

我目前正在建立一个列出各种餐馆的项目。在我的项目中,我使用主表视图显示餐馆列表,点击单元格后,它通过segue传输到View控制器,显示有关餐厅的基本信息。在详细的View Controller中,有一个名为“Offers”的按钮,在点击它时会打开另一个tableview,显示该餐厅的一系列优惠。 (请参阅附图)

到目前为止,我只能查看我的餐馆列表,详细信息显示View Controller,但我不知道如何显示每家餐厅的优惠清单。 请帮助我,并提前感谢你。

代码: 餐厅/酒吧模型:

import Foundation
import Firebase
import FirebaseDatabase

struct Bar{
    let id: String
    let barName: String
    let barAddress: String
    let barMainImage: String
    let barInfo: String
    let barFullAddress: String
    let averagePrice: String

    let disabledIcon: String
    let parkingIcon: String
    let wifiIcon: String
    let offerImage: String

    static func bar(from snapshot: DataSnapshot) -> Bar?{
        let barDict = snapshot.value as? [String : AnyObject] ?? [:]
        guard let barName = barDict["bar_name"] as? String,
        let barAddress = barDict["bar_short_address"] as? String,
        let barMainImage = barDict["bar_main_image"] as? String,
        let barInfo = barDict["bar_info"] as? String,
        let barFullAddress = barDict["bar_full_address"] as? String,
        let averagePrice = barDict["average_price"] as? String,

        let disabledIcon = barDict["disabled_icon"] as? String,
        let parkingIcon = barDict["parking_icon"] as? String,
        let wifiIcon = barDict["wifi_icon"] as? String,
 let offers = barDict["offers"] as? [String:Any],
    let offerImage = offers["offer_image"] as? String,
        let id = String(snapshot.key)
        else {return nil}
    let bar = Bar (id: id, barName: barName, barAddress: barAddress, barMainImage: barMainImage, barInfo: barInfo, barFullAddress: barFullAddress, averagePrice: averagePrice, disabledIcon: disabledIcon, parkingIcon: parkingIcon, wifiIcon : wifiIcon, offerImage: offerImage)

    return bar
}

}

第一个表格视图控制器 - 列出所有餐厅:

import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import FirebaseStorage
import SDWebImage

class MainTableVC: UITableViewController {


@IBOutlet weak var MenuBar: UIBarButtonItem!

@IBOutlet weak var cityButton: UIButton!

var ref: DatabaseReference!
var bars = [Bar]()
var selectedBar: Bar?
var refreshTableView = UIRefreshControl()
var selectedCity:String!


override func viewDidLoad() {
    super.viewDidLoad()

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem()

    //back button title removal
    self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil)


    // SlideOutMenu
    MenuBar.target = self.revealViewController()
    MenuBar.action = #selector(SWRevealViewController.revealToggle(_:))
    self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())

    ref = Database.database().reference()

    fetchBars()
    // for pull to refresh
    refreshTableView.tintColor = UIColor.white
    self.tableView.addSubview(refreshTableView)
    refreshTableView.addTarget(self, action: #selector(MainTableVC.refreshData), for: UIControlEvents.valueChanged)


}


// for pull to refress
func refreshData() {
    //removes data before updating and entering new one
    self.bars.removeAll()
    ref.child("Paris").observe(.childAdded, with: { (snapshot) in
        guard let bar = Bar.bar(from: snapshot) else {return}
        self.bars.append(bar)
        self.refreshTableView.endRefreshing()
        self.tableView.reloadData()
    })
 }

func fetchBars(){

    ref.child("Paris").observe(.childAdded, with: { (snapshot) in
        guard let bar = Bar.bar(from: snapshot) else {return}
        self.bars.append(bar)
        self.tableView.reloadData()
    })
    self.refreshTableView.endRefreshing()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

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


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

    let bar = bars[indexPath.row]
    cell.RestName.text = bar.barName
    cell.RestAddress.text = bar.barAddress
    cell.RestImage.sd_setImage(with: URL(string: bar.barMainImage))


    return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    selectedBar = bars[indexPath.row]
    performSegue(withIdentifier: "DetailView", sender: self)
}


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "DetailView", let bar = selectedBar{
        let detailVC = segue.destination as! DetailViewController
        detailVC.selectedBar = bar
    }
}

详情视图控制器 - 列出每家餐厅的所有详细信息:

import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import FirebaseStorage
import SDWebImage

class DetailViewController: UIViewController {

@IBOutlet weak var MyScroll: UIScrollView!




@IBOutlet weak var RestDetailView: UIView!
@IBOutlet weak var restName: UILabel!

@IBOutlet weak var restTypeOfFood: UILabel!

@IBOutlet weak var restClockImage: UIImageView!

@IBOutlet weak var restOpenHours: UILabel!

@IBOutlet weak var restInfoView: UIView!

@IBOutlet weak var averagePrice: UILabel!

@IBOutlet weak var InfoAboutRest: UILabel!

@IBOutlet weak var FullAddressLabel: UILabel!

@IBOutlet weak var disabledIcon: UIImageView!

@IBOutlet weak var parkingIcon: UIImageView!

@IBOutlet weak var wifiIcon: UIImageView!

@IBOutlet weak var OpeningHoursLabel: UILabel!





@IBOutlet weak var ImageViewD: UIImageView!

var selectedBar:Bar?

override func viewDidLoad() {
    super.viewDidLoad()


    self.RestDetailView.layer.borderColor = UIColor.white.cgColor
    self.RestDetailView.layer.borderWidth = 1
    self.restInfoView.layer.borderColor = UIColor.white.cgColor
    self.restInfoView.layer.borderWidth = 1

    if let bar = selectedBar{
        restName.text = bar.barName
        ImageViewD.sd_setImage(with: URL(string: bar.barMainImage))
        InfoAboutRest.text = bar.barInfo
        averagePrice.text = bar.averagePrice
        FullAddressLabel.text = bar.barFullAddress
        disabledIcon.sd_setImage(with: URL(string: bar.disabledIcon))
        parkingIcon.sd_setImage(with: URL(string: bar.parkingIcon))
        wifiIcon.sd_setImage(with: URL(string: bar.wifiIcon))

    }

}






/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

图片

[Firebase树] [1] [MainStoryBoard] [2]

OffersTableView:


import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import FirebaseStorage
import SDWebImage


class OffersTableVC: UITableViewController {
var ref: DatabaseReference!
var bars = [Bar]()
var selectedBar: Bar?

override func viewDidLoad() {
    super.viewDidLoad()

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    fetchBars()
}
func fetchBars(){

    ref.child("aktau").observe(.childAdded, with: { (snapshot) in
        guard let bar = Bar.bar(from: snapshot) else {return}
        self.bars.append(bar)
        self.tableView.reloadData()
    })

}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

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


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

    let bar = bars[indexPath.row]
    cell.offerImageView.sd_setImage(with: URL(string: bar.offerImage))
    return cell
}

我模型中的错误:

ModelError

1 个答案:

答案 0 :(得分:0)

你必须解析" offer"喜欢

let offers = barDict["offers"] as? [String:Any]

然后你必须像

一样解析这个词典
    var offersArray = [Offer]()

    for item in offers {

    guard let offerimage = item["offerImage"] as? String, ... {
      var offer = Offer(offerimage)
      offersArray.append(offer)
    }
}


class Offer {

 let offerImageUrl:String
 // Other Properties

   init(string: offerImageUrl){
     self.offerImageUrl = offerImageurl
     //Other Properties
   }
}

我希望你明白我的想法。现在你有一个包含你的优惠的数组:)