Swift - Retrieving auto assigned ID from Firebase - swift

I'm making a simple app which displays the name of each item inside this database, and when the user swipes left, they can delete the item, along with its name and quantity. When this happens, I need to delete that entire node from the database. How would I obtain their IDs to do this?
For example, when user swipes left on Apple, I need to obtain the ID KXsWXi1XE5cwdJiJQnj and delete that whole section.
Thanks in advance.

You will likely want to associate the ID of a cell to the actual cell. You can do this by creating a list of IDs and appending to that list each ID from your database. So when the user selects the second item in the list, you can access the associated ID by going to the second item in the list of IDs.
For example:
var listOfIDs = [String]() // goes in public scope of class
//Adding data from database to populate cells
for child in snapshot.children {
// Add child info to your list of info being displayed
// HERE YOU WOULD APPEND listOfIDs by this child's ID
}

Try this:-
FIRDatabase.database().reference().child("ShoppingItems").observeSingleEvent(of: .value, with: {(Snapshot) in
if let snapDict = Snapshot.value as? [String:AnyObject]{
for each in snapDict{
let key = each.key
print(key)
}
}
})
To delete:-
Delete from the local database i.e array and then call this function
FIRDatabase.database().reference().child("ShoppingItems/\(key)").removeValue()
Where key is your key for the value or cell.

Related

Firebase BarcodeScanner get parent/other nodes of a specific child

In my app I have certain items in my firebase database like this:
Categories
Category1
Item1
id: item1
name: Item 1 name
barcode: 473088034839
item2
id: item2
name: Item 2 name
barcode: 564084724885
These items are in a collectionview. I have another view where I'm using a barcodeScanner to scan the barcode of the products in my database. The barcode scanner works great and I'm able to print the barcode of scanned products to the console, and it matches the codes in "barcode" in my database.
The problem is I'm trying to get the name if the item I'm scanning. With the following code I'm able to find/match the barcode I'm scanning with the code in my database:
let someBarcode = Database.database().reference().child("Categories").queryOrdered(byChild: "barcode").queryEqual(toValue: code)
print(someBarcode)
code is the string of numbers I get from scanning a barcode. After finding the correct barcode in my database, how can I then retrieve the current Items id and/or name?
Firebase Realtime Database queries work on a flat list. They can order/filter on a property at a fixed path under each direct child under the location you query on.
So in your scenario you could query across all categories on a fixed property of each category, or you can query a specific category for items with a specific property value. But you can't search across all categories for the ones that contain an item with a certain property value.
The solution is to create an data structure that allows the specific query, typically either by flattening the list you already have, or by adding an additional structure to allow the lookup.
For more on this, see:
Firebase Query Double Nested
Firebase query if child of child contains a value
With Franks help I managed to create a new node in my firebase DB with the barcode codes:
Barcodes
item1 : code1
item2 : code2
item3 : code3
Then I used the following function to
func scanner(_ controller: BarcodeScannerViewController, didCaptureCode code: String, type: String) {
// get product id from Barcodes
Database.database().reference().child("barcodes")
.observeSingleEvent(of: .value) { (snapshot) in
guard let dict = snapshot.value as? [String: Any] else {
self.showNotFoundMessage()
return
}
for (key, value) in dict {
let valueString = "\(value)"
if valueString == code {
self.getProduct(id: key)
return
}
}
self.showNotFoundMessage()
}
}

Retriving data from database

First time asking a question here, so sorry if I do it wrong.
Anyways. I'm using Firebase Database to store "Results" in my Quiz app. When data is store it looks like this
Results
-LjQ34gs7QoL1GMufiMsaddclose
Score: xx
UserName: xx
-LjQ3NeCoDGob8wnhstH
Score: xx
UserName: xx
I would like to access score and username from it and display it in a HighScore tableview. Problem is - I can get the "Results" node, but because of the id of the results (ie LjQ34gs7QoL1GMufiMsaddclose) I don't know how to access the score and username.
I got the data snapshot​, but not sure how to "bypass" the id to get to score and username.
Hope I made it at least a bit clear, what the problem is.
let ref = Database.database().reference().child("Results")
ref.observe(.value) { (DataSnapshot) in
print(DataSnapshot.value as Any)
}
You current code gets you a single snapshot with the results of all users. You'll need to loop over the child snapshots to get the result of each user, and then look up their specific properties with childSnapshot(byName:):
let ref = Database.database().reference().child("Results")
ref.observe(.value) { (snapshot) in
for case let userSnapshot as DataSnapshot in snapshot.children {
print(userSnapshot.childSnapshot(forPath: "Score").value)
}
}
Also see:
How to get all child data from firebase without knowing the path
Iterate through nested snapshot children in Firebase using Swift
How do I loop through and get all the keys of the nested nodes in firebase?
Retrieving Data using Firebase Swift
And probably some more from this list.

How to implement a firebase transaction

I have this schema in my firebase :
I have a node articles under it have the ids of users, under one id I have a wishlist name then the articles and the wishlist info, So when I want to change the wishlist name I take the children of the node I want to change then I create w new one with the new name and the same children then I remove the old wishlist. So I want to create a transaction to do all the work in same time or not to do it at all if there is a bad connection because I can loose the data if the operation is interrupted. This is my current code and how I can put the operation in a firebase transaction. Thank you for your help !
func updateWishlist(wishlist:WishList,newName:String){
if((reachability.connection == .wifi) || (reachability.connection == .cellular)){
self.showProgressView()
let child = self.ref.child("Articles").child((user!.uid)!)
self.ref.child("Articles").child((user!.uid)!).child(wishlist.name) .updateChildValues(["name":newName]) { error, _ in
if(error == nil){
//create new node with new name
let oldName=wishlist.name
child.child(wishlist.name).observeSingleEvent(of: .value, with: { (snapshot) in self.ref.child("Articles").child((GlobalVar.user!.uid)!).child(newName).setValue(snapshot.value as! [String : Any]) { error, _ in
if(error == nil){
self.dismissHUD(isAnimated: true)
self.title=newName
self.showMessage("Wishlist modifier !", type: .success, options: [.position(.bottom)])
self.ref.child("Articles").child((GlobalVar.user!.uid)!).child(oldName).removeValue()
}
else{
self.dismissHUD(isAnimated: true)
print("update wishlist name transaction failed")
}
}
user?.wishLists[self.passedWishlistIndex!].name=newName
})
}
self.dismissHUD(isAnimated: true)
}
}
}
This issue really comes down to this statement
I want to change the wishlist name I take the children (out) of the node I
want to change then I create a new one with the new name and the same
children then I remove the old wishlist
The fix is to not use dynamic data as node keys. Restructuring your data will eliminate the need for a transaction.
The wishlist name should be stored as a child of the node with a key created with .childByAutoId.
To clarify, your structure is currently this
Articles
article_0
dadoune //wish list name
solo //with list name
articles
xxx
yyy
zzz
artical_1
artical_2
and here's what will work; move the wish list name to a child node.
Articles
article_0
-Jk0ksk0kj9sdfsdf //wish list key created with .childByAutoId
wish_list_name: "dadoune" //store the name as a child
-Jyl909m9mm3o99jt //wish list key created with .childByAutoId
wish_list_name: "solo" //store the name as a child
articles
xxx
yyy
zzz
article_1
article_2
By storing the dynamic wish list name as a child, you can simply change it whenever you want without having to read the node, delete the node, change the name, and re-write the node.

How to know which index a child was added to an ordered FirebaseQuery

Using Firebase and Swift SDK
I just started with Firebase and wanted to display a list of Conversations ordered by last_update. The following query works fine :
let query = Database.database().reference().child("chat").child("channels").queryOrdered(byChild: "last_update")
query.observe(DataEventType.childAdded) { (snapshot: DataSnapshot) in
if let value = snapshot.value as? [String: Any?] {
log.debug("added channel: \(snapshot.key) : \(value)")
//add object to array, insertRow in tableview
}
}
The first time my view is loaded, each item arrives in the correct order specified by the query, so the display is ok. But if I create a new channel, it does appear at the end of the tableview, because I just add it at the end of the array and just call insertRow on my table view. My question is : is there any mecanism that give us the new inserted position of the DataSnapshot ?
Same question for DataEventType.childMoved : we get to know that a snapshot has moved, but how to know where it has moved ??
I finally end up using FirebaseUI, especially the submodule FirebaseDatabaseUI (see the github repo here)
They provide a FUITableViewDataSource, you just create a query and pass it to it, it will handle everything like sorting etc. I also used FUIArray, which is simply an array backed by a query, with a delegate for added / deleted / moved / update events (and proper indexes).

Indexing relational data correctly in Firebase Swift

I would like to check that I am indexing my relational data correctly, as I am trying to wrap my head around Firebase. I have a two way relationship between users and addresses, both are one to one. The idea is that the user node is initially created with just their email, then when they add their address, a key for the addressID is added to the user node and simultaneously, a key for the userID is added to the address node. This is meant to be similar to how it is recommended in the "Structure Data" section of the Firebsae docs (at the bottom). However, to identify the address within the user node and to identify the user within the address node, I have used their auto generated key (i.e. address: userAutoID, user: addressAutoID; rather than userAutoID: true and addressAutoID: true; as the former is more descriptive and easier to understand. The use of an autogenerated ID as a key doesnt indicate what the key represents). The JSON structure is as follows (both nodes are children of the top-most node):
As you can see the address possesses the user's ID, and the user possesses the address ID. I feel as though the code I have used to achieve this is protracted and I could be going about this the wrong way. The code is triggered when the user has filled out a form for their address and they press submit. Hence, the User node exists before the address node. I use a for loop to sequentially obtain the key of each address that exists, which i then feed into another query, which then looks to find if the current user's ID exists whithin the current address node as the value of the userID key. If this is true, then I set the ID of the current address to the value of the addressID within the current users associated node. Here is the code:
self.rootRef.child("Addresses").observeSingleEvent(of: .value, with: { snapshot in
for address in snapshot.children {
guard let addressSnapshot = address as? FIRDataSnapshot else {
print("failed to get addressSnapshot")
return
}
let addressSnapshotKey = addressSnapshot.key
self.rootRef.child("Addresses").child(addressSnapshotKey).observeSingleEvent(of: .value, with: { snapshot in
guard let snapshotValue = snapshot.value as? [String: AnyObject] else {
print("error getting snapshotValue")
return
}
let userID = FIRAuth.auth()?.currentUser?.uid
if (snapshotValue["userID"] as! String) == userID {
let correctKey = addressSnapshotKey
let userRef = self.rootRef.child("Users").child(userID!)
userRef.child("addressID").setValue(correctKey)
}
})
}
})
I can see that running two queries from one piece of code, may become expensive when the User and Addresses node become very large. Any feedback would be greatly appreciated!
I would reuse the auto generated User key as the key under Addresses as well.
- Users
- xyz (auto generated)
- email: jo#jo.com
- Addresses
- xyz (use the previously created id here too)
- street
- author
- lat
- lon