用户点击表格行时如何向Firebase数据添加计数

在我的应用程序中,用户在HomeViewController中选择A或B,然后在LocationViewController中,他们从表视图中选择一个地方,最后ResultViewController汇总其他用户的选票。

我被困在LocationViewController中将用户选择注册到Firebase

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if userVote == "A" {
        // add vote count by 1 to A of Location ABC in Firebase
        // register this vote to user's path too
    } else {
        // add vote count by 1 to B of Location ABC in Firebase
        // register this vote to user's path too
    }
}

我是iOS,Swift和Firebase的新手,在AppCoda本教程帮助下,我设法做到了一点。任何帮助表示赞赏:)

这是我的解决方案,没有要在其中注册对用户ID的投票的部分。不确定这是否是最有效的方法,请随时发表评论:

var businesses = [Business]()

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let indexPath = tableView.indexPathForSelectedRow!
    let business = businesses[indexPath.row]
    // Get the Firebase key of the selected row
    let businessId = business.businessKey
    // Get the path to the vote data
    let voteARef = ref.childByAppendingPath(businessId).childByAppendingPath("voteA")
    let voteBRef = ref.childByAppendingPath(businessId).childByAppendingPath("voteB")

    if userVote == "voteA" {

        voteARef.runTransactionBlock({
            (currentData:FMutableData!) in
            var value = currentData.value as? Int
            if (value == nil) {
                value = 0
            }
            currentData.value = value! + 1
            return FTransactionResult.successWithValue(currentData)
        })


    } else {

        voteBRef.runTransactionBlock({
            (currentData:FMutableData!) in
            var value = currentData.value as? Int
            if (value == nil) {
                value = 0
            }
            currentData.value = value! + 1
            return FTransactionResult.successWithValue(currentData)
        })
    }

    performSegueWithIdentifier("ResultSegue", sender: self)
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章