Mariah Mariah - 3 months ago 9
Swift Question

Structuring the JSON File in Dashboard (Swift and Firebase Project)

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

I'm having a view called add device, where the registered user can add only 5 devices at most.
Simply he/she can enter the device name, description, category and add the image then click on add device button.

Here's the current dashboard that contains the info of the registered users:

{
"UserProfile" : {
"1EJ8QmEQBJfBez7PMADbftCjVff1" : {
"city" : "الرياض",
"email" : "noura@gmail.com",
"name" : "نوره",
"phone" : "0564695353"
},
"97PUAcUC5UYxLpBOLnC4yQjxiEf2" : {
"city" : "Riyadh",
"email" : "mama2017@gmail.com",
"name" : "مريم",
"phone" : "0534260282"
}
}
}


I wanted to add another node in the dashboard called Devices like this:

{
"Devices" : {
"1EJ8QmEQBJfBez7PMADbftCjVff1" : {
"Device1": {
"DeviceName" : "",
"Description" : "",
"Category" : "",
"ImageURL" : ""
},
"Device2": {
"DeviceName" : "",
"Description" : "",
"Category" : "",
"ImageURL" : ""
} , until device 5
}
}


Here's what I have done in the button so far:

@IBAction func AddDeviceButton(sender: AnyObject) {

if DeviceName.text == "" || Description.text == "" || ImageView.image == nil {
let alert = UIAlertController(title: "عذرًا", message:"يجب عليك تعبئة معلومات الجهاز كاملة", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "نعم", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}

} 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)
return
}

let profileImageUrl = metadata?.downloadURL()?.absoluteString

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

self.ref.child("Devices").child(user!.uid).setValue(DeviceInfo)

})






}

}


In this line:

self.ref.child("Devices").child(user!.uid).setValue(DeviceInfo)


The view could not recognize the uid!

Why?

How can I add the node Device1, Device2, etc?

Answer

Just replace

self.ref.child("Devices").child(user!.uid).setValue(DeviceInfo)

with

self.ref.child("Devices").child(FIRAuth.auth()!.currentUser!.uid).setValue(DeviceInfo)