如果Firebase快照为nil,则为UITableView Cell的默认值

时间:2017-05-31 17:14:51

标签: swift uitableview firebase firebase-realtime-database

我环顾四周,我无法弄清楚这一点。

如果Firebase快照返回 nil

,我正尝试设置tableView Cell的默认值

示例:

创建快照以显示Firebase数据库中的所有事件名称 在tableView中使用dequeReusableCell。

但如果快照返回nil ,则tableView将返回1个单元格,其标签上写着“抱歉,没有事件。

这是我的firebase快照代码。如果快照使用 print()语句返回nil,则此代码当前会处理。

func populateTableView(){
        let uid = Auth.auth().currentUser?.uid
        ref = Database.database().reference()
        ref.child("events").child(uid!).child(currentDate).observeSingleEvent(of: .value, with: { (snapshot) in

            self.events = []
            if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
                for snap in snapshot {
                    //print("SNAP: \(snap)")
                    if let postDict = snap.value as? Dictionary<String, AnyObject> {
                        let key = snap.key
                        let event = Event(postKey: key, postData: postDict)
                        self.events.append(event)
                        //print(self.events)
                    }
                }

            }

            if !snapshot.exists() {

                self.eventStatus = false
                self.tableView.reloadData()
                print("No Event here")

            } else {

                self.eventStatus = true
                self.tableView.reloadData()
            }

        })

    }

firebase对象存储在Event类中并存储在字典中。我不认为这个代码是必需的,但这里是更多上下文的事件类代码。

import Foundation
import Firebase

class Event {

    var ref: DatabaseReference!

    private var _description: String!
    private var _imageUrl: String!
    private var _eventTitle: String!
    private var _eventType: String!
    private var _eventTime: String!
    private var _eventStartDate: String!
    private var _eventEndDate: String!
    private var _monthlyRepeat: String!
    private var _weeklyRepeat: String!
    private var _eventColor: String!

    private var _postKey: String!
    private var _postRef: DatabaseReference!

    var description: String {
        return _description
    }

    var imageUrl: String {
        return _imageUrl
    }

    var eventTitle: String {
        return _eventTitle
    }

    var eventType: String {
        return _eventType
    }

    var eventTime: String {
        return _eventTime
    }

    var eventStartDate: String {
        return _eventStartDate
    }

    var eventEndDate: String {
        return _eventEndDate
    }

    var monthlyRepeat: String {
        return _monthlyRepeat
    }

    var weeklyRepeat: String {
        return _weeklyRepeat
    }

    var eventColor: String {
        return _eventColor
    }

    var postKey: String {
        return _postKey
    }



    init(postKey: String, postData: Dictionary<String, AnyObject>) {
        self._postKey = postKey

        if let description = postData["description"] as? String {
            self._description = description
        }

        if let imageUrl = postData["event_Image_URL"] as? String {
            self._imageUrl = imageUrl
        }

        if let eventTitle = postData["event_Title"] as? String {
            self._eventTitle = eventTitle
        }

        if let eventType = postData["event_Type"] as? String {
            self._eventType = eventType
        }

        if let eventTime = postData["event_Time"] as? String {
            self._eventTime = eventTime
        }

        if let eventStartDate = postData["start_Date"] as? String {
            self._eventStartDate = eventStartDate
        }

        if let eventEndDate = postData["end_Date"] as? String {
            self._eventEndDate = eventEndDate
        }

        if let monthlyRepeat = postData["monthly_Repeat"] as? String {
            self._monthlyRepeat = monthlyRepeat
        }

        if let weeklyRepeat = postData["weekly_Repeat"] as? String {
            self._weeklyRepeat = weeklyRepeat
        }

        if let eventColor = postData["color"] as? String {
            self._eventColor = eventColor
        }

        let uid = Auth.auth().currentUser?.uid
        ref = Database.database().reference()
        let eventRef = ref.child("events").child(uid!).child("Monday May, 29")


        _postRef = eventRef.child(_postKey)

    }



}

1 个答案:

答案 0 :(得分:0)

解决此问题的最简单方法是向UILabel添加标题ViewcController,并在快照不可用时更改文字。

或者,如果由于某种原因这对你不起作用,你可以试试这个:

我没有检查过这个,但我可能会让你走上正轨。

首先,您需要更改populateTableView方法,以便即使快照没有结果也会创建events数组。这样,events数组计数将为1(并且一行将添加到tableView),即使快照没有结果。

populateTableView(){
    let uid = Auth.auth().currentUser?.uid
    ref = Database.database().reference()
    ref.child("events").child(uid!).child(currentDate).observeSingleEvent(of: .value, with: { (snapshot) in

        self.events = []
        if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
            for snap in snapshot {
                //print("SNAP: \(snap)")
                if let postDict = snap.value as? Dictionary<String, AnyObject> {
                    let key = snap.key
                    let event = Event(postKey: key, postData: postDict)
                    self.events.append(event)
                    //print(self.events)
                }
            }
        }
        else{ // Snapshot does not exist
            let postDict: Dictionary<String, AnyObject>  // Add an empty Dictionary
            let key = -1 // Or what ever value you could not possibly expect
            let event = Event(postKey: key, postData: postDict)
            self.events.append(event)
            self.tableView.reloadData()
            print("No Event here")
        }
    })
}

请注意,当快照无效或可用时,您可以为Dictionary数组添加一个空keyevents值。

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

您需要创建两个具有唯一标识符的自定义单元格。

现在你可以&#34;实际上&#34;填充与此类似的tableView

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let event = events.[indexPath.row]
    let conditionKey = event.key
    if(conditionKey == -1){ // or whatever value you gave in populateTableView to indicate that snapshot did not exist
        let cell = tableView.dequeueReusableCell(withIdentifier: "identifierCellNotSoGood", for: indexPath) as! CustomCellNotSoGood
        cell.noSnapShotLabel1.text = "Sorry, there are no events."
        return cell
    }
    else{
        let cell = tableView.dequeueReusableCell(withIdentifier: "identifierCellAllGood", for: indexPath) as! CustomCellAllGood
        cell.yourCustomLabel1.text = event.key      // Or whatever data you are displaying 
        cell.sourCustomLabel2.text = event.event    // Or whatever data you are displaying 
        return cell
    }

    return UITableViewCell
}

如果您需要处理表格单元格的选择,可以执行以下操作:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // get rid of the ugly highlighting
    tableView.deselectRow(at: indexPath, animated: false)

    let event = events.[indexPath.row
    let conditionKey = event.key
    if(conditionKey == -1){ // or whatever value you gave in populateTableView to indicate that snapshot did not exist
        // Do what you need or not
    }
    else{
        // Do something meaningful with your database
        doSomething(withEventData: event)
    }
}