Query Firebase Database With Swift - ios

I am trying to query an entry in my firebase realtime database with Swift to basically see if an entry exists with the owner = 33206. My current code is not returning what I need, how can I fix this query?
Here is my code:
var promoCodes: DatabaseReference {
return ref.child("PromoCodes")
}
func getIsAffiliate() {
promoCodes.child("owner").queryEqual(toValue: 33206).observeSingleEvent(of: .value) { snapshot in
print("SNAP HERE: \(snapshot)")
AffiliateService.isAffiliate = snapshot == nil
}
}
Output: SNAP HERE: Snap (owner) <null>

The snapshot passed to your code will never be nil. To check if there are matching nodes, you can check snapshot.exists() instead.

Related

Firebase + iOS: Receiving stale data using observeSingleEvent without using isPersistence = true

I currently use observeSingleEvent to fetch data periodically in our game. It seems that the client is receiving stale data at times while using this method. From what I have read, I believe this should only happen if isPersistence = true, which is not the case. Is this still expected behavior? Shouldn't I receive fresh data each time I query? Thanks in advance.
EDIT: More detailed query:
for levelNumber in 1...numberOfLevels
{
ref.child(pathToLevelData + "/" + levelNumber).queryOrderedByValue().queryStarting(atValue:
highScore+1).observeSingleEvent(of: .value, with: { snapshot in
for child in snapshot.children
{
let snap = child as! DataSnapshot
guard let value = snap.value as? Int else { return }
// Process value, but it is not always fresh data from Firebase
}
})
}

Update a particular subchild in firebase realtime database swift 4

The screenshot above is of the database i created. I successfully am able to upload and retreive data through code but i dont know how to update a subchild. For instance if i want to update the subchild user_name how can i acheive this in swift any snippet would be appreciated.
ref.child("USERS").child(email).child("user_name").setValue("new user name"){
(error:Error?, ref:DatabaseReference) in
if let error = error {
//error
} else {
//do stuff
}
}
}
It's simple, you need just call setValue on the child like this:
ref.observeSingleEvent(of: .value, with: { (snapshot) in
self.ref.child("USERS").child(email).child("user_name").setValue("new User Name")
})

How does control flow work when retrieving Information from Firebase?

var ergebnisBluetezeit = Set<String>()
let refBluetezeit = rootRef.child("Pflanzen").child("Eigenschaften").child("Blütezeit")
refBluetezeit.child("Februar").observeSingleEvent(of: .value, with: { snapshot in
for plant in snapshot.children {
self.ergebnisBluetezeit.insert((plant as AnyObject).value)
}
})
print(ergebnisBluetezeit)
I want to retrieve Data from my Firebase Database. The Retrieving Process does work already, but the following confuses me: the current output from the print is an empty set, but when i use the var ergebnisBluetezeit elsewhere (for example setup a button, which action is to print ergebnisBluetezeit), it is filled. When i put the print in the for loop, it does print the right output, too.
I seem to not have understood the control flow here, so my Question:
How can i use the Set where the print statement is at the moment?
Thanks for your help.
It's the logic of asynchronous calls
print("1") // empty
refBluetezeit.child("Februar").observeSingleEvent(of: .value, with: { snapshot in
print("3") // empty
for plant in snapshot.children {
self.ergebnisBluetezeit.insert((plant as AnyObject).value)
}
print(ergebnisBluetezeit) // not empty
})
print("2") // empty
the value is empty until the request finishes regardless of where in code ordering you run the print , as the numbering above in order 1 , 2 , 3 to know when it finishes you can use completions like
func getData(completion:#escaping() -> ()) {
let refBluetezeit = rootRef.child("Pflanzen").child("Eigenschaften").child("Blütezeit")
refBluetezeit.child("Februar").observeSingleEvent(of: .value, with: { snapshot in
for plant in snapshot.children {
self.ergebnisBluetezeit.insert((plant as AnyObject).value)
}
completion()
})
}
And call
getData {
print(ergebnisBluetezeit)
}

Swift Firebase Delete Post

I need help deleting a post from firebase. I have the post id key and everything and have been trying all the methods and nothing works. I want to delete the the 3rd child in "posts". I have been trying all types of code. The code below doesn't even throw an error. Not sure what to do. I am getting the values by using a indexpath.row tag.
let postID = self.posts[sender.tag].postID
Database.database().reference().child("posts").child(uid!).child(postID).removeValue { error, _ in
if error != nil {
print("error \(error)")
}
}
Testing
I tried this, and this deletes everything under that user...
Database.database().reference().child("posts").child(uid!).queryOrdered(byChild: "postID").queryEqual(toValue: postID).observe(.value, with: { snapshot in
if snapshot.exists() {
snapshot.ref.removeValue()
print(snapshot)
} else {
print("snapshot doesn't exist")
}
})
check the value of the reference you want to delete by
Database.database().reference().child("posts").child(uid!).child(postID).observe(.value, with: { snapshot in
print(snapshot.value)
})
you can also put them together to check if it's happening locally or not
Database.database().reference().child("posts").child(uid!).child(postID).removeValue()
Database.database().reference().child("posts").child(uid!).child(postID).observe(.value, with: { snapshot in
print(snapshot.value)
})
if it's correct you may don't have access to delete node from the database, check database rules tab in the firebase console
as a last resort you may check your connection because if there is slow connection firebase will cache the updates you make until there is a good connection to sync to the cloud
This works.
Database.database().reference().child("posts").child(uid!).queryOrdered(byChild: "postID").queryEqual(toValue: postID).observe(.childAdded, with: { snapshot in
if snapshot.exists() {
snapshot.ref.removeValue()
print(snapshot)
} else {
print("snapshot doesn't exist")
}
})

Retrieving data with .Value and .ChildAdded

I have a list of data to retrieve from Firebase, using Swift.
I tried to get the data using .Value and Firebase returns a dictionary with the IDs of each item and for each ID the info associated.
The endpoint I am calling is /ideas.
let ideasRef = firebase.childByAppendingPath(IdeaStructure.PATH_IDEAS)
ideasRef.observeEventOfType(.Value, withBlock: { snapshot in
print(snapshot.value)
}, withCancelBlock: { error in
print(error.description)
})
In order to optimize this, I changed with .ChildAdded. In this case I get only the single item without the ID associated.
Is it possible to get also the ID of each item using .ChildAdded?
If not, how can I save the ID generated by Firebase into each item? Currently I am saving each item in this way:
let ideasRef = firebase.childByAppendingPath(IdeaStructure.PATH_IDEAS).childByAutoId()
let idea = [
IdeaStructure.FIELD_MESSAGE: message,
IdeaStructure.FIELD_CREATOR_ID: userId,
IdeaStructure.FIELD_CREATION_DATE: NSDate().formattedISO8601
]
ideasRef.setValue(idea)
To get the key of the snapshot, access its key property:
let ideasRef = firebase.childByAppendingPath(IdeaStructure.PATH_IDEAS)
ideasRef.observeEventOfType(.Value, withBlock: { snapshot in
print(snapshot.key)
print(snapshot.value)
}, withCancelBlock: { error in
print(error.description)
})
This and many more topics are covered in Firebase's excellent programming guide for iOS.

Resources