如何将多个所选项目发送到服务器?

时间:2019-12-17 23:37:34

标签: swift xcode firebase-realtime-database uicollectionview

因此,我收集了一个视图,该视图允许用户选择多个类别来展示他们的照片。当我选择一个单元格时,打印语句运行良好,它将按预期方式打印单元格名称childValue。当我提交帖子时,它仅上载到数据库的最后选择的索引。

问题的一个示例-如果我选择“打印”和“绿色”类别,则照片将仅张贴“绿色”,因为它是最后选择的索引。如何保存用户所做的所有选择并将帖子发送到所选的childValues?



    var selectedCategoryValue = ""

    var trend: Trend!
    var style: Style!

    // When a cell is selected, the postID will be added to the correct childvalue that is relevent to the post
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if collectionView == trendCollectionView {


        switch selectedSegmentIndex {

        case 0: self.trend = femaleTrends[indexPath.row]
        print("You selected row \(trend.childValue)")


        self.selectedCategoryValue = trend.childValue


        case 1: self.trend = maleTrends[indexPath.row]
            print("You selected row \(trend.childValue)")
            self.selectedCategoryValue = trend.childValue

             default: break

        }


        } else {

          // Once I figure out how to store multiple selected values, I will complete else statement
            switch selectedSegmentIndex {

            case 0: self.style = femaleStyles[indexPath.row]
            case 1: self.style = maleStyles[indexPath.row]

                 default: break

            }


        }


    }

这里是按下提交按钮并将照片上传到服务器时使用的功能

    func uploadPostToCategory(withPostId postId: String) {

        let selectedValue = [postId: 1]
            switch trend.gender {
            case .female:
                // add postId to childValue based on cell selection
                FEMALE_TRENDS_REF.child(selectedCategoryValue).updateChildValues(selectedValue)

            case.male:
                MALE_TRENDS_REF.child(selectedCategoryValue).updateChildValues(selectedValue)

            }



        }

在此处的集合视图单元格中处理了isSelected


   override var isSelected: Bool {
        didSet{
            if self.isSelected {
                trendCheckmark.isHidden = false

            }
            else {
                trendCheckmark.isHidden = true

            }
        }
    }

1 个答案:

答案 0 :(得分:0)

似乎您只是在选择单元格时更改了变量selectedCategoryValue,并将其设置为附加数组。

所以:

var selectedCategoryValues = [String]()

然后选择一个:

self.selectedCategoryValues.append(trend.childValue)

,在您的uploadPostToCategory函数中,您将需要一个for循环来遍历所有selectedCategoryValue,如下所示:

func uploadPostToCategory(withPostId postId: String) {
    for selectedCategoryValue in selectedCategoryValues {
    let selectedValue = [postId: 1]
        switch trend.gender {
        case .female:
            // add postId to childValue based on cell selection
            FEMALE_TRENDS_REF.child(selectedCategoryValue).updateChildValues(selectedValue)

        case.male:
            MALE_TRENDS_REF.child(selectedCategoryValue).updateChildValues(selectedValue)

        }
       }

    }

您还可以查看:self.collectionView.indexPathsForSelectedItems