Mariah Mariah - 3 months ago 7
Swift Question

Uploading user info to firebase Error (swift project)

I'm working on iOS application using swift and firebase.

The user can register from a register view by his/her name, email, password and some other info, here's the Users node in the dashboard, each user should have a sub-node called user-devices to store the ids' for the user devices:

{
"Users": {
"1EJ8QmEQBJfBez7PMADbftCjVff1":{
"Email":"",
"Phone":"",
"Name":"",
"City":"",
"UserDevices": {
"1EJ8QmEQBJfBez7PM":"",
"1EJ8QmEQBJfBdfkgj":"",
"1EJ8QmEQBJfBdfkgj":""
}
},
"97PUAcUC5UYxLpBOLnC4yQjxiEf2": {
"Email":"",
"Phone":"",
"Name":"",
"City":"",
"UserDevices": {
"1EJ8Qgjhdghhgjhgd":"",
"sjdhfkhfhfhBdfkgj":""
}
}
}
}


There's another view called add device, where the registered user can add a device. Simply he/she can enter the device name, description, category and add the image then click on add device button.

Each user can add only five devices.

So there's another node called devices like this:

"Devices": {
"1EJ8QmEQBJfBez7PMADbftCjVff1":{
"DeviceName": "",
"Description": "",
"Category": "",
"ImageURL": ""
},
"97PUAcUC5UYxLpBOLnC4yQjxiEf2":{
"DeviceName": "",
"Description": "",
"Category": "",
"ImageURL": ""
}
}


I have tried to turn this structure into code.

Here's the part of register button:

else {

FIRAuth.auth()?.signInWithEmail(self.EmailTF.text!, password: self.PasswordTF.text!, completion: { (user: FIRUser?, error: NSError?) in
if let error = error {
print(error.localizedDescription)
} else {

self.ref.child("UserProfile").child(user!.uid).setValue([
"email": self.EmailTF.text!,
"name" : self.NameTF.text!,
"phone": self.PhoneTF.text!,
"city" : self.CityTF.text!,

])
self.ref.child("UserProfile").child("UserDevices")
print("Sucess")

}


And here's the part of the add device button where I have the problems:

else {


let imageName = NSUUID().UUIDString
let storageRef = FIRStorage.storage().reference().child("Devices_images").child("\(imageName).png")

if let uploadData = UIImagePNGRepresentation(self.ImageView.image!) {
storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
if error != nil {
print(error)

} else {

//Here I want to check of the number of the ids' of UserDevices if less than or equal to 5 the user can add device, otherwise an alert will appear to the user!
if self.ref.child("UserProfile").child("UserDevices").child(id) <= 5 {

let profileImageUrl = metadata?.downloadURL()?.absoluteString
let DeviceInfo = [
"ImageUrl":profileImageUrl!,
"DeviceName":self.DeviceName.text!,
"Description":self.Description.text!,
"Category":self.itemSelected
]
self.ref.child("Devices").childByAutoId().setValue(DeviceInfo)
self.ref.child("UserProfile").child("UserDevices").setValue(id)

} else {

print("You can only enter five devices maximum")
//alert message

}
}

})





}

}


*Is this the correct way to access to the UserDevices ids'?

self.ref.child("UserProfile").child("UserDevices").child(id)

Answer

Try Something like this:-

 let DeviceInfo = [
                    "ImageUrl":profileImageUrl!,
                    "DeviceName":self.DeviceName.text!,
                    "Description":self.Description.text!,
                    "Category":self.itemSelected
                    ]

    self.ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid).observeSingleEventOfType(.Value, withBlock: {(snapShot) in

        if snapShot.exists(){

            let numberOfDevicesAlreadyInTheDB = snapShot.childrenCount

            if numberOfDevicesAlreadyInTheDB < 5{

                let newDevice = String("Device\(numberOfDevicesAlreadyInTheDB+1)")

                let userDeviceRef = self.ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid)

                userDeviceRef.observeSingleEventOfType(.Value, withBlock: {(userDevices) in

                    if let userDeviceDict = userDevices.value as? NSMutableDictionary{

                        userDeviceDict.setObject(DeviceInfo,forKey: newDevice)

                        userDeviceRef.setValue(userDeviceDict)
                    }
                })
             }
                else{
                    //Show Alert that user cant enter Devices Anymore
                }
            }else{
              self.ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid).setValue(["Device1" : DeviceInfo])
            }
        }) 
Comments