Salvando matriz no Firebase

Estou usando o Firebase 3.0 como meu back-end e preciso salvar todos os meususer.uid em um filho separado que precisa ser um NSArray e, em seguida, recupere essa matriz usando um loop for!

É assim que estou salvando meus dados: criei uma classe separada para o FIRController, que está lidando com todo o armazenamento e recuperação de banco de dados e armazenamento.

func signUpUserWithBasicInfo(emailId : String! , password : String!, username : String!, age : String, gender : String!, backpackerType : String, info : [String : AnyObject], completionBlock : (() -> Void)){

    print("fir signup did recieve")
    FIRAuth.auth()?.createUserWithEmail(emailId, password: password, completion: {
        user,error in

        if error != nil{
            print("error encountered while backend email signup Handshake : \(error)")
            print("")
            self.delegate.firShowAlert("Error signing you up", Message: "Please check your network or this email already exist!")

        }else{
            print("uploading database")
            self.profilePictureUploading(info, completionBlock: {

                FIRControllerClass.ref.child("UserProfile").child(user!.uid).setValue([
                    "username" : username,
                    "email" : emailId,
                    "age" : age,
                    "gender" : gender,
                    "password" : password,
                    "typeOfBackpacker" : backpackerType
                    ])

                completionBlock()

            })
        }
    })
}

func profilePictureUploading(infoOnThePicture : [String : AnyObject],completionBlock : (()->Void)) {

    if let referenceUrl = infoOnThePicture[UIImagePickerControllerReferenceURL] {
        print(referenceUrl)
        let assets = PHAsset.fetchAssetsWithALAssetURLs([referenceUrl as! NSURL], options: nil)
        print(assets)
        let asset = assets.firstObject
        print(asset)
        asset?.requestContentEditingInputWithOptions(nil, completionHandler: { (ContentEditingInput, infoOfThePicture)  in

            let imageFile = ContentEditingInput?.fullSizeImageURL
            print("imagefile : \(imageFile)")

            let filePath = FIRAuth.auth()!.currentUser!.uid +  "/\(Int(NSDate.timeIntervalSinceReferenceDate() * 1000))/\(imageFile!.lastPathComponent!)"
            print("filePath : \(filePath)")

                FIRControllerClass.storageRef.child("ProfilePictures").child(filePath).putFile(imageFile!, metadata: nil, completion: { (metadata, error) in

                         if error != nil{

                            print("error in uploading image : \(error)")
                            self.delegate.firShowAlert("Error Uploading Your Profile Pic", Message: "Please check your network!")
                         }

                          else{

                                print("metadata in : \(metadata!)")
                                print(metadata?.downloadURL())
                                print("The pic has been uploaded")
                                print("download url : \(metadata?.downloadURL())")

                                self.uploadSuccess(metadata!, storagePath: filePath)

                                completionBlock()

                }

            })
        })

    } else {
            print("No reference URL found!")
    }
}

Como eu criaria um filho no meu back-end que serviria como matriz e como posso recuperar essa matriz?

Minha base de firmas JSON ESTRUTURA: -

{
  "UserId" : [ 1, 
    "Sq5EDvVOsQWkLylEx3GrBdEsIN92",
    "xC4jCJmobUcqghq8C3SI1XT0UPk1",
    "D8QmnOSH6vRYiMujKNXngzhdn992",
    "riHjon6wknOmALwf0Z0Ri5aOMA82",
    "fKqlb88MKsYCE43xy7D51qH6jqH3",
    "aCgAFAGDIgWRSUu9a2aMo9HtnnD3",
    "iicKACGo8RaeTSEggKPB0sU2Bme2",
    "qJ2c8AcEYzVkJKLl13N92tyKnbz2"
    ],
  "UserProfile" : {
    "D8QmnOSH6vRYiMujKNXngzhdn992" : {
      "age" : "12",
      "email" : "[email protected]",
      "gender" : "f",
      "password" : "123454321",
      "typeOfBackpacker" : "dummy",
      "username" : "duummyy1"
    },
    "Sq5EDvVOsQWkLylEx3GrBdEsIN92" : {
      "age" : "121",
      "email" : "[email protected]",
      "gender" : "gjhg",
      "password" : "123454321",
      "typeOfBackpacker" : "chef",
      "username" : "hgfgh"
    },
    "aCgAFAGDIgWRSUu9a2aMo9HtnnD3" : {
      "age" : "24",
      "email" : "[email protected]",
      "gender" : "F",
      "password" : "123454321",
      "typeOfBackpacker" : "Group",
      "username" : "Cathy"
      },
      etc
}

eu também preciso adicionar uma matriz deno of friends no meu banco de dados (matriz). A única razão pela qual estou usando o loop for é para que eu possa exibir os detalhes de todos os usuários para meu usuário (além dele) usando a matriz userId que criei no meu banco de dados, que na verdade é o nó pai para todos os seus respectivos bancos de dados de usuários.

É assim que eu estou acrescentandoUserId no meu banco de dados: -

func retrieveUserIdsArray(completionBlock : ((appendedArr : NSMutableArray) -> Void)){

    var appendedArray : NSMutableArray = []

    FIRControllerClass.ref.child("UserId").observeEventType(FIRDataEventType.Value, withBlock: {(snapshot) in

        if let userIdDetails = snapshot.value as? NSMutableArray{

        userIdDetails.addObject((FIRAuth.auth()?.currentUser?.uid)!)
        appendedArray = userIdDetails

        completionBlock(appendedArr: appendedArray)

        }
    })
} 

que é chamado nesta função: -

    func signUpUserWithBasicInfo(emailId : String! , password : String!, username : String!, age : String, gender : String!, backpackerType : String, info : [String : AnyObject], completionBlock : (() -> Void)){

    print("fir signup did recieve")

    FIRAuth.auth()?.createUserWithEmail(emailId, password: password, completion: {
        user,error in

        if error != nil{

            print("error encountered while backend email signup Handshake : \(error)")

            print("")

            self.delegate.firShowAlert("Error signing you up", Message: "Please check your network or this email already exist!")

        }else{

            print("uploading database")

            self.profilePictureUploading(info, completionBlock: {

                FIRControllerClass.ref.child("UserProfile").child(user!.uid).setValue([
                    "username" : username,
                    "email" : emailId,
                    "age" : age,
                    "gender" : gender,
                    "password" : password,
                    "typeOfBackpacker" : backpackerType
                    ])


                var a = 0

                self.retrieveUserIdsArray({ (appendedArr) in

                    a += 1

                    print("The appended array is : \(appendedArr)")

                    if a == 1{

                        FIRControllerClass.ref.child("UserId").setValue(appendedArr)

                    }else{

                        completionBlock()

                    }
                })
            })
        }
    })
}

A razão pela qual eu useia variável é enfrentar o loop infinito que estava causando (eu sei que é apenas um hack, por enquanto ..)

Aberto a qualquer maneira melhor de resolver isso! ..

questionAnswers(1)

yourAnswerToTheQuestion