Bypass unique auto ID created by Firebase. Swift 3.0 - swift

When I upload an Image, it is automatically update to database child(user.uid).child(newImage).childAutoID.setValue()
This is my json node
Users
WOhpPzlHCzYximWyBXas3Prg2rL2
NewImage
-KSE4ZcvqhFeWmuRQjjI
-KSEGLazKbfPePkCBFbe
-KSEGNVimH7GACRyXbo4
-KSEGO4gfLGOv0erTXA5
-KSENPeq7Oa5cru7gKum
Inside one autoID, This is the Json tree
-KSE4ZcvqhFeWmuRQjjI
DownloadUrl: "abcd.com"
timestamp: 21-09-2016
When I try to get value from DownloadUrl, I use child("Users") but can't child through user uid, anyways I can't child through autoUID which is created by Firebase. Does anyone have any experience. Thank you

Swift 2:
FIRDatabase.database().reference().child("Users/\(FIRAuth.auth()!.currentUser!.uid)/NewImage").observeSingleEventOfType(.Value , withBlock : {(imagesSnap) in
if let imagesDict = imagesSnap.value as? [String:AnyObject] {
for each in imagesDict{
print(each.0) // your autoId
print(each.1) // your imageDetails for that autoId
}
}
})
Swift 3:
FIRDatabase.database().reference().child("Users/\(FIRAuth.auth()!.currentUser!.uid)/NewImage").observeSingleEvent(of: .value, with : {(imagesSnap) in
if let imagesDict = imagesSnap.value as? [String:AnyObject] {
for each in imagesDict{
print(each.0) // your autoId
print(each.1) // your imageDetails for that autoId
}
}
})
But if you are looking for the autoID that contains a specific key value pair Read last part of this answer

Related

Write data to with userID and read data with userID

I want to write data to firebase with a userID, because later I only want to retrieve the data the user saved. The first problem is when I read data to firebase only the values change, but I want that the values append to firebase with the userID.
I only want to retrieve the data with the UserId of the current user, but when I load it I get all informations from all users.
I already tried to change the childadded or valuetype.
I already tried to set after the first child "SavedWoman" an other child with the current userID but it don't work.
let userID = Auth.auth().currentUser?.uid
let SavedProduct : [String: Any] = ["ImageURL": FImage1[picturenumber], "Price" : Price[picturenumber]]
Database.database().reference().child("SavedWoman").child(userID!).setValue(SavedProduct)
I also tried:
refData = Database.database().reference().child("SavedWoman") /*here I already tried to set the userID */
refData.observeSingleEvent(of: .value, with: { (snapchot) in
if snapchot.childrenCount>0 {
for data in snapchot.children.allObjects as![DataSnapshot] {
let DataObject = data.value as? [String: AnyObject]
let ImageObject = DataObject?["ImageURL"]
let PriceObject = DataObject?["Price"]
let data1 = DataModel(ImageURL: ImageObject as! String?, Price: PriceObject as! String?)
self.DataList.append(data1)
}
self.tableView.reloadData()
}
})

How to retrieve data's name in Firebase

I'm not sure if "data's name" is the correct way to call it but here is my problem:
I have a table like this
I want to create 2 arrays that contain the ID (0001, 0040) and the Date (13-9-2017).
Because IDs are generated automatically so I don't know how to query
What I've tried:
func retrievingPresciptionID(){
let userID = appDelegate.userIDFirebase
Database
.database()
.reference()
.child("UserInformation")
.child(userID)
.child("prescriptionID")
.observeSingleEvent(of: .value, with: {snapshot in
if snapshot.exists(){
for id in snapshot.children {
self.prescriptionID.append((id as AnyObject).key)
}
print(self.prescriptionID)
}else{
print("snapshot failed")
}
})
}
It printed snapshot failed
Assuming we get the dict for the prescriptionIDs..
for prescription in prescriptionIDs {
IDArray.append(prescription.key)
dateArray.append(prescription.value)
}
The problem is you are not getting your dict to create your two arrays. Find the node that is missing.

When retrieving data from Firebase Database, <null> is returned: "Snap (...) <null>"

I'm a relatively new Swift programmer and am using Firebase for the first time so please excuse any misunderstandings I may have and my lack of knowledge about terminology.
I am attempting to retrieve data about a user that is stored in a database (email and username).
The code successfully finds the userID in the database. The userID is then used in order to navigate into the directory containing the username and email. It stores those values in snapshot.
For some reason, when snapshot is printed, it shows the userID but the contents of the directory (username and password) are shown as <null>. I am certain that the directory I am attempting to access and retrieve data from exists and is not empty (it contains a username and email). I wantsnapshot to store the username and email, but printing shows that it is not doing so correctly and I cannot figure out why.
here is my code block:
func checkIfUserIsLoggedIn() {
if Auth.auth().currentUser?.uid == nil {
perform(#selector(handleLogout), with: nil, afterDelay: 0)
} else {
let uid = Auth.auth().currentUser?.uid;
Database.database().reference().child("Users").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
print(snapshot)
if let dictionary = snapshot.value as?[String:AnyObject] {
self.userLabel.text = dictionary["name"] as? String
}
}, withCancel: nil)
}
}
and here is what is being printed to the console:
Snap (ywU56lTAUhRpl3csQGI8W8WmQRf1) <null>
Here is the database entry I am attempting to reach and log to snapshot:
I'm a new Stack Overflow user and don't have enough experience on the site to be allowed to embed images in posts, so this is the external link
Thanks for reading, any help would be much appreciated!!
Your reference in Firebase is to "users", but you are using .child("Users") in your code. Make sure your lookup matches case to your node. I find it best to create a reference to that node and use it for writing to and reading from.
let usersRef = Database.Database().reference().child("users")
Snap (ywU56lTAUhRpl3csQGI8W8WmQRf1) <null> the portion in parenthesis refers to the end node of what you are trying to observe. In this case it refers to uid!.
if u want to get username or email then you make first the model class for
Example:-
class User: NSObject {
var name: String?
var email: String?
}
then user firebase methed observeSingleEvent
FIRDatabase.database().reference().child("user").child(uid).observeSingleEvent(of: .value, with: { (snapShot) in
if let dictionary = snapShot.value as? [String: Any]{
// self.navigationItem.title = dictionary["name"] as? String
let user = User()
user.setValuesForKeys(dictionary)
self.setUpNavigationBarWithUser(user: user)
}
})`
if it is not finding your asking values, you are asking wrong directory. check firebase db child name it must be exactly like in your code ("Users")

Retrieve data from an unknown child name with Firebase and Swift

I'm using Firebase as the database for my IOS app. I want to retrieve data of several users from the database.
Here is my database organization:
Users
UserID1
Location: value1
UserID2
location: Value2
...
I want to retrieve the location data of all the users of the database.
The basic snapshot fonction
ref.child("Users").child("").child("Location").observe(.value, with: {
snapshot in
for Location in snapshot.children {
self.locationsArray.append((Location as AnyObject).key)
}
print(self.locationsArray)
})
My question is: how can I retrieve all the Locations even if I don't specify (I can't) the userID that is the name of a child before? Thanks.
Here's a code snippet that retrieves and prints the uid of each user and their location.
We can further refine our results with a .query
let usersRef = ref.child("users")
usersRef.observeSingleEvent(of: .value, with: { (snapshot) in
for snap in snapshot.children {
let userSnap = snap as! FIRDataSnapshot
let uid = userSnap.key //the uid of each user
let userDict = userSnap.value as! [String:AnyObject] //child data
let location = userDict["Location"] as! String
print("key = \(uid) is at location = \(location)")
}
})
It is not possible with Firebase to retrieve just the Location.
There are a lot of option, but I see two that fits better in your case:
Get everything from all users, and then manage in your code what you want;
Create another dictionary only with users id and location.
The second option would be like:
UsersLocation
UserID1:Location1
UserID2:Location2
So every time you change your main array you need to change this too.

How to delete from Firebase database

Hi i have followed this tutorial: https://www.youtube.com/watch?v=XIQsQ2injLo
This explains how to save and retrieve from the database, but not how to delete. I am wondering how to delete the database node that belongs to the cell that is being deleted. Thanks
Edit. Code updated for Swift 3 and Swift 4.
I'm always using the remove with completion handler:
static let ref = Database.database().reference()
static func remove(child: String) {
let ref = self.ref.child(child)
ref.removeValue { error, _ in
print(error)
}
}
So for example if I want to delete the following value:
I call my function: remove(child: "mixcloudLinks")
If I want to go deeper and delete for example "added":
I need to change the function a little bit.
static func remove(parentA: String, parentB: String, child: String) {
self.ref.child("mixcloudLinks").child(parentA).child(parentB).child(child)
ref.removeValue { error, _ in
print(error)
}
}
Called like:
let parentA = "DDD30E1E-8478-AA4E-FF79-1A2371B70700"
let parentB = "-KSCRJGNPZrTYpjpZIRC"
let child = "added"
remove(parentA: parentA, parentB: parentB, child: child)
This would delete just the key/value "added"
EDIT
In case of autoID, you need to save the autoID into your Dictionary to be able to use it later.
This is for example one of my functions:
func store(item: MyClassObject) {
var item = item.toJson()
let ref = self.ref.child("MyParentFolder").childByAutoId()
item["uuid"] = ref.key // here I'm saving the autoID key into the dictionary to be able to delete this item later
ref.setValue(item) { error, _ in
if let error = error {
print(error)
}
}
}
Because then I'm having the autoID as part of my dictionary and am able to delete it later:
Then I can use it like .child(MyClassObject.uuid).remove... which is then the automatic generated id.
we can store the randomly generated id as the user id in the database and retrieve that to delete
for e.g. :
let key = ref?.childByAutoId().key
let post = ["uid": key,
"name": myName,
"task": myTask]
ref?.child(key!).setValue(post)
in order to delete
setvalue of the id as nil
for e.g. :
var key = [string]()
ref?.child(key[indexPath.row]).setValue(nil)
key.remove(at: indexPath.row)
myArray.remove(at: indexPath.row)
myTable.reloadData()