Getting an optional firebase database value when it shouldn't be optional - ios

I am running the following query to get a value from the snapshot, but the value is returning as optional.
ref.child("PGroups").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
let groupName = String(rest.childSnapshotForPath("/GroupName").value)
print(groupName)
})
and am getting the following printed statement: "Optional(Name)" as appoosed to just: "Name"

Simply add an exclamation point to tell the compiler to unwrap the optional:
print(groupName!) should print "Name"
Alternatively you could also change your code to something like this:
ref.child("PGroups").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
let snapshotValue = snapshot.value as! [String: Any]
let groupName = snapshotValue["GroupName"] as! String
print(groupName)
})

Related

Ambiguous use of 'subscript' despide the same code working elsewhere?

I have code which retrieves users from firebase. The problem is that I get the error:
Ambiguous use of 'subscript'
On the lines, I marked in the block below. The weird thing is that the exact same code is currently in another project in nearly identical circumstances and it does not get this error.
The code is below:
func retriveUsers() {
let ref = Database.database().reference()
ref.child("user2").queryOrderedByKey().observeSingleEvent(of: .value, with: { (snapshot) in
let users = snapshot.value as! [String : AnyObject]
self.users.removeAll()
for (_, value) in users {
if let uid = value["uid"] as? String {//Error
if uid != Auth.auth().currentUser?.uid {
let userToShow = User()
if let fullName = value["full name"] as? String {//Error
userToShow.fullName = fullName
userToShow.userID = uid
self.users.append(userToShow)
}
}
}
}
})
print(users.count, " This is the number of users retrived the first looks like: ", users[0].userID)
}
I have looked here and here and neiother has solved my problem. What is the solution here?
The compiler doesn't know the type of value in users, you provided AnyObject which is ambiguous because it can be both an array (index subscripted) or dictionary (key subscripted).
Be more specific and tell the compiler that value is a dictionary, by the way it's always supposed to be Any not AnyObject and check the type safely
if let users = snapshot.value as? [String : [String:Any]] { ...

Swift Retrieve Firebase Data from Database

I'm trying to retrieve data from Firebase but I'm having issues.
let refEmployees = Database.database().reference(withPath: "Employees")
refEmployees.child("Logan").observeSingleEvent(of: .value, with: {
snapshot in
let shift = snapshot.value as? String
self.shifts.append(shift!)
self.workSchedule.reloadData()
})
That is my code, my database looks like this.
When I run it, I get
fatal error: unexpectedly found nil while unwrapping an Optional value
Any ideas? I'm stumped. I also can add information to the database at the same time and change to childAdded and the information loads properly.
Usually I never try to get the reference "withPath", but by child.
I would Try to do it like this:
let ref = Database.database().reference().child("Employees").child("Logan")
On the other part, is a bad practice to force unwrap optionals that you don't know you are actually going to get, I would change the closure to:
ref.observeSingleEvent(of: .value, with: {
snapshot in
guard let shift = snapshot.value as? String else {
print("Value is Nil or not String")
return
}
self.shifts.append(shift)
self.workSchedule.reloadData()
})
Like someone in the comments said, may be a good idea to print the optional value first to see if you are actually getting the value that you need from the database.
Hope this helps
let refEmployees = Data`base.database().reference()
refEmployees,child("Employees").child("Logan").observeSingleEvent(of: .value, with: {
snapshot in
let shift = snapshot.value! as! [String : AnyObject]
let dictKeys = [String](snapshot.keys)
//Will give you all` keys from DB 0,1,2,3,4,5,6
let dictValues = [AnyObject](snapshot.values)
//will give you` all values "off", "off", "2-10"..."off"
//use keys or values append in array if you want as I could not understand what you are trying to save in self.shifts
self.shifts.append(shift!)
self.workSchedule.reloadData()
})

Firebase iOS Swift retrive list of favourites with data from other node

Pictures
-pictureID
-- name
-- date
Like
-pictureID
-- userID: true
-- userID: true
likePerUser
-userID
--pictureID: true
--pictureID: true
Users
-userID
-- name
-- lastname
I would like to retrieve all picture that current user has liked.
I did:
ref.child("likePerUser").child(FIRAuth.auth()!.currentUser!.uid).observeSingleEvent(of: .value, with: { (snap) in
for item1 in snap.children{
let firstItem1 = (snap: item1 as! FIRDataSnapshot)
print("key favourites\(firstItem1.key)")
let firstId = firstItem1.key
self.ref.child("pictures").child(firstId).observeSingleEvent(of: .value, with: { (snapshot) in
for item in snapshot.children{
let firstItem = (snapshot: item as! FIRDataSnapshot)
print("key pictures \(firstItem.key)")
let dict = firstItem.value as! [String: Any
let name = dict["name"] as! String
print(name)
}
Even, If it seems that firstId has the right value each time,
I always get an error:
Could not cast value of type '__NSCFBoolean' (0x110dae5b8) to
'NSDictionary' (0x110daf288).
Please help....
I solved doing this:
if let dictionary = snapshot.value as? NSDictionary {
if let name = dictionary["nome"] as? String {
print(name)
}
}
This questions helped me: Swift - Could not cast value of type '__NSCFString' to 'NSDictionary'
Also i didn't need to iterate once more.
let dict = firstItem.value as! [String: Any
Here is where you attempt to cast a value as a dictionary. It's unclear whether the value is a dictionary based upon the model of the database you've shared. But there's a good chance that if you print firstItem.value.debugDescription, you will see that the value it isn't a dictionary object.

How to read Firebase child value?

I'm a newbie to coding and Swift.
I'm trying to retrieve the value of house1Colour from my Firebase database in my app. I've tried these methods so far.
let eg = FIRDatabase.database().reference(withPath: "test")
(when I use this I get a THREAD 1 Signal SIGABRT error, I'm not sure why)
and:
var test:String!
FIRDatabase.database().reference().child("house1Colour").observeSingleEvent(of: .value, with: {(snap) in
if let snapDict = snap.value as? Dictionary <String, AnyObject>{
self.test = snapDict["house1Colour"] as! String
print(self.test)
}
})
None of them work.
The value of FIRDatabase.database().reference().child("house1Colour") is just the string since you already specified the key house1Colour.
Therefore you should be able to just:
if let snapString = snap.value as? String {
print(snapString)
}

how do I set a variable to get value from Firebase database structure in Swift

I am now struggling with Firebase database.
For example here's my database structure
"Menus" : {
"Day1" : {
"mealDes" : "delicious Thai food",
"date" : "2016.10.20",
"mealname" : "kakoon"
},
and I need to set a variable to get the value of "date".
something like : print(theDateVar) //get 2016.10.20
I tried some observeSingleEvent and observe method, they're not working!
DataService.ds.REF_MENUS.observeSingleEvent(of: .value, with: { snapshot in
if let date = snapshot.childSnapshot(forPath: "menuDate") as? String {
print ("date is \(date)")
}
})
I know retrieving data from database is frequently asked,
but all the question i searched is not helping
please help me out :(, I spend half of my weekend on this but still...
UPDATE
Hi, it totally worked!
my code now is looks like the following :
FIRDatabase.database().reference().child("Menus/Day1").observeSingleEvent(of: .value, with: {(snap) in
if let snapDict = snap.value as? Dictionary <String, AnyObject>{
let date = snapDict["mealPic"] as! String
let OrderInfo = DataService.ds.REF_ORDER
let USERUID = FIRAuth.auth()!.currentUser!.uid
let userinfo = OrderInfo.child("date").child(USERUID).child("data")
userinfo.child("address").setValue("SomeRandomAddress")
userinfo.child("phonenumber").setValue("666888")
}
})
but what if I want to set the address value and the phone number value as the value i have in other node (user)
"Menus": {
"User" : {
"WbxT2bBgcnYOEn2YUqpvh4mtxvo2" : {
"address" : "taipei City ",
"phonenumber" : "0933555666",
"provider" : "Firebase"
}
do i use observeSingleEvent again in observeSingleEvent ?
Try using :-
FIRDatabase.database().reference().child("menus/Day1").observeSingleEvent(of: .value, with: {(snap) in
print(snap)
if let snapDict = snap.value as? [String:AnyObject]{
let date = snapDict["date"] as! String
print(date)
}
})

Resources