Firebase retrieve single value in child loop - swift

I'm retrieving a few items from Firebase using .ChildAdded when I print the child in the loop I see all the keys and values and they all start with snap problem is when I go head and print(child.value["myKeyhere"]) I get a system error. How can I solve this
Firebase child result print from loop * I want to retrieve 'age' only*
Snap (age) 54
Snap (email) User1#gmail.com
Snap (firstname) User2Firstname
Snap (lastname) User2Lastname
Snap (profilePic) users/profilePhoto/fKNTGRGfmgdZwtHUyJxOjnKXZzx2.jpg
Snap (receivePostRequest) {
lat = "37.32550194";
long = "-122.01974475";
status = 1;
tags = {
beauty = 0;
heathcare = 0;
house = 1;
housekeeper = 0;
scholar = 0;
student = 0;
};
}
my code
let dbref = FIRDatabase.database().reference()
dbref.child("users").queryOrderedByChild("receivePostRequest/status").queryEqualToValue(true).observeEventType(.ChildAdded, withBlock: { snapshot in
var helprInfo = [[String: AnyObject]]()
for child in snapshot.children {
print(child)
}
})

child.value["myKeyhere"]as! String

Related

List remains empty after adding elements in flutter firebase

I have tried to add session model to a list of sessions like this but the list reamains empty. My database has the following structure
void getData()
{
var Ref = fb.ref("sessions");
Ref.onValue.listen((event){
var snapshot = event.snapshot;
Iterable<DataSnapshot> children = snapshot.children;
for( var k in children)
{
var ref = fb.ref("sessions/${k.key}");
ref.onValue.listen((event) {
var snp = event.snapshot;
Iterable<DataSnapshot> chi = snp.children;
for(var v in chi)
{
Session s = new Session();
s.timeStamp = v.key.toString();
s.date = k.key.toString();
s.session = v.value.toString();
sessions.add(s);
}
});
}
sessions.refresh();
print(sessions);
totalsessions.value = sessions.length;
});
}
Output
I/flutter (11551): []
Data is loaded from Firebase (and most modern cloud APIs) asynchronously, and while that is going on your main code continues to execute.
It's easiest to see this if you run in a debugger or add some logging statements like this:
var ref = fb.ref("sessions");
print("Before attaching first onValue");
ref.onValue.listen((event) {
print("In first onValue");
var snapshot = event.snapshot;
Iterable<DataSnapshot> children = snapshot.children;
for( var k in children) {
var ref = fb.ref("sessions/${k.key}");
ref.onValue.listen((event) {
print("In second onValue");
});
}
print("After second onValue");
});
print("After first onValue");
When you run this code, it prints:
Before first onValue
After first onValue
In first onValue
After second onValue
In second onValue
This may not be what you expect, but it does explain why your sessions is empty when you print it. By the time your print(sessions) runs, the sessions.add(s) hasn't happened yet.
This problem is incredibly common, and the solution is always the same: any code that needs the data from the database has to be inside the callback that runs when that data is available.
So:
var ref = fb.ref("sessions");
ref.onValue.listen((event){
var snapshot = event.snapshot;
Iterable<DataSnapshot> children = snapshot.children;
for(var k in children) {
var ref = fb.ref("sessions/${k.key}");
ref.onValue.listen((event) {
var snp = event.snapshot;
Iterable<DataSnapshot> chi = snp.children;
for(var v in chi) {
Session s = new Session();
s.timeStamp = v.key.toString();
s.date = k.key.toString();
s.session = v.value.toString();
sessions.add(s);
}
sessions.refresh();
print(sessions);
totalsessions.value = sessions.length;
});
}
});
In your case though, we can simplify the code a lot further. Since you get a read sessions, the snapshot you get contains all data under that path in the database. So you don't need additional listeners to get each specific sessions, but can get the data from the children.
Something like:
var ref = fb.ref("sessions");
ref.onValue.listen((event){
var snapshot = event.snapshot;
Iterable<DataSnapshot> children = snapshot.children;
for(var child in children) {
Iterable<DataSnapshot> grandchildren = child.children;
for(var grandchild in grandchildren) {
Session s = new Session();
s.timeStamp = grandchild.key.toString();
s.date = child.key.toString();
s.session = grandchild.value.toString();
sessions.add(s);
}
sessions.refresh();
print(sessions);
totalsessions.value = sessions.length;
}
});

How to add variables from a firebase snapshot

I know this question has been ask several times but none of the solutions work for me. here is my snap shot
Snap (CaseExtend) {
NYxdSlq8yOgQd3phssRlD = {
CaseMinute = {
WMKuImjuH0qPIGJhHHJKv = {
caseMinute = "";
dateTime = "Dec 1, 2021 12:20 PM";
minuteId = WMKuImjuH0qPIGJhHHJKv;
userId = OtRFaqilTigWvEkUCASvCoEegny1;
};
};
CaseParticipant = {
3f7nqmcWFTenePkEB9KoMHLzVtk2 = {
userId = 3f7nqmcWFTenePkEB9KoMHLzVtk2;
};
OtRFaqilTigWvEkUCASvCoEegny1 = {
userId = OtRFaqilTigWvEkUCASvCoEegny1;
};
};
caseId = Oj7TwzDC3HQMJKyTb8Ebi;
caseNumber = TEST;
court = "Labour Tribunal";
courtRoomNo = "";
date = "2021-12-01";
extendId = NYxdSlq8yOgQd3phssRlD;
extendStatus = "Not Extend";
location = "";
participantCount = 2;
profilePicture = "https://firebasestorage.googleapis.com/v0/b/lege-155e1.appspot.com/o/Profile%20Pictures%2FOtRFaqilTigWvEkUCASvCoEegny1.jpg?alt=media&token=676226fa-638b-4175-a8d5-247095f6b86a";
step = TBM;
time = "";
userId = OtRFaqilTigWvEkUCASvCoEegny1;
};
}
and i retrieve the snapshot using following code,
ref.child("CaseExtend").queryOrdered(byChild: "userId").queryEqual(toValue: "OtRFaqilTigWvEkUCASvCoEegny1" ).observe(.value, with: { (DataSnapshot) in
})
i want to add the caseID, caseNumber, date.. and other values for different variables. is there anyway i can do this?
first of all you are getting all data in casetExtend node all the variables you want to assign is not under that node. for that you need to navigate one level of child node.
ref.child("CaseExtend").queryOrdered(byChild: "userId").queryEqual(toValue: "OtRFaqilTigWvEkUCASvCoEegny1" ).observe(.value, with: { (snapshot) in
for caseSnapshot in snapshot.children.allObjects as! [DataSnapshot] {
let dict = caseSnapshot.value as? [String: AnyObject] // assign the snapshot to a dictionary
let court = dict!["court"] as? String ?? "unknown"; // assign the variable
}
})

How do I retrieve the files from localstorage by the extension name ".log"?

I am new to angular/js/ionic. I have a really quick question.
How do I retrieve data from localstorage when I don't really know the index name? I just want to grab whatever ends with ".log"?
I understand that the code below will try to retrieve the data by the index 'notes'.
var logFile = angular.fromJson(window.localStorage['notes'] || '[]');
var localLogFile = function() {
for(var i = 0; i < localStorage.length; i++) {
var keyName = localStorage.key(i);
var extension = keyName.substring(keyName.lastIndexOf("."));
if(extension == ".log") {
return localStorage.getItem(keyName);
}
}
};
var logFile = angular.fromJson(localLogFile());

Load Specific data from JSON with Random Values Swift

I am using firebase and I am trying to retrieve data from Firebase Database which is working well however when I call "postDict" I get.
["-KPZAOg58kUdqwYMzlDJ":
{
description = jpeg;
listingImageURL = "https://firebasestorage.googleapis.com/v0/b/hype-central.appspot.com/o/lidsafstings%2FC73FdfB8A0-968df7-44DB-B96B-A10DC1E3A2B7.png?alt=media&token=b6e296f2-8854-4b76-9bfc-470dfd69d11f2f";
location = jpeg;
price = 54;
title = jpeg;
userDisplayName = "Brandon YOIO";
userid = pRuwvL7WyzQpY0G22ZLYCmTTemB3;
},
"-KPZ0yLhcfLvP9YWNjbC": {
description = "Description ofvaroe";
listingImageURL = "https://firebadfasestorage.googleapis.com/v0/b/hype-central.appspot.com/o/listings%2F0ACdasfCD645-2E2C-4936-B3DF-37EC55AA0157.png?alt=media&token=b321dasff42f-75b5-4eb3-b129-b0a902cc5926";
location = Vancouver;
price = 34;
title = eclipse;
userDisplayName = "Brandon YOIO";
userid = pRuwvL7WyzQpY0G22ZLYCmTTemB3;
},
"-KPoCsNS63JZdbTJIdaP": {
description = Brandon;
listingImageURL = "https://firebadasfsestorage.googleapis.com/v0/b/hype-central.appspot.com/o/listings%2FOptional(%22pRuwvL7WyzQpY0G22ZLYCmTTemB3%22)%2F3EACE28E-D28A-464A-B6D0-FB502E9dafsB4775.jpeg?alt=media&token=1d45bc7b-7273-4d33-8ccd-755f3102a23c";
location = BRANDON;
price = BRANDON;
title = BRANDON;
userDisplayName = "Brandon YOIO";
userid = pRuwvL7WyzQpY0G22ZLYCmTTemB3;
},
"-KP_Y7ug7hwrHtW6VNqV": {
description = "Description ofvaroe";
listingImageURL = "https://firebaseddasfstorage.googleapis.com/v0/b/hype-central.appspot.com/o/listings%2FC5daf7991BA-D7E0-4C8A-96E7-0DB17EEBABD7.jpeg?alt=media&token=efd03b4d-6964-4685-9b48-5ed36a4ceb59";
location = "";
price = "";
title = "";
userDisplayName = "Brandon Mayhew";
userid = pRuwvL7WyzQpY0G22ZLYCmTTemB3;
}]
If I call "postDict["-KPZAOg58kUdqwYMzlDJ"]["title"]" It will print the title which is exactly what I want however how do I get an array of all the titles in this JSON format (not just the title of "-KPZAOg58kUdqwYMzlDJ").
How do I get all the title's?
Use :-
rootRef.observeEventType(.Value, withBlock: {(postDictionary) in
if let postDict = postDictionary.value as? [String:AnyObject]{
for each in postDict as [String:AnyObject]{
let autoID = each.0
rootRef.child(autoID).observeEventType(.Value, withBlock: {(specificPost) in
//RETRIEVE YOUR DATA
})
}
}
})
PS:- I have used rootRef as you have not specified your parent nodes in your JSON structure :)

Shouldn't wrapped optionals always print with the keyword 'Optional'?

Code
func downloadimages (URL: NSURL) {
let request = NSMutableURLRequest ( URL: URL)
request.HTTPMethod = "GET"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error ) in
guard error == nil else {
print("we have an error from Server")
return
}
var JSONData: AnyObject!
do {
JSONData = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) /* as? [String:AnyObject?] */
} catch {
print (" We had a Parsing issue '\(data)'")
return
}
print(JSONData)// Doesn't print 'Optional' word?????
print(JSONData!)
if let something = JSONData!["photos"]{
print (something!)
print(something) // This prints the word 'Optional as well'
}
Output
//printed unwrapped--NOT GOOD! -- I didn't unwrap it with '!'
{
photos = {
page = 1;
pages = 622374;
perpage = 1;
photo = (
{
farm = 8;
id = 27765969370;
isfamily = 0;
isfriend = 0;
ispublic = 1;
owner = "8262787#N07";
secret = 6daeee7d68;
server = 7233;
title = "Stars, Planets and Lightning Bugs";
}
);
total = 622374;
};
stat = ok;
}
// unwrapped printed--Good!
{
photos = {
page = 1;
pages = 622374;
perpage = 1;
photo = (
{
farm = 8;
id = 27765969370;
isfamily = 0;
isfriend = 0;
ispublic = 1;
owner = "8262787#N07";
secret = 6daeee7d68;
server = 7233;
title = "Stars, Planets and Lightning Bugs";
}
);
total = 622374;
};
stat = ok;
}
//Unwrapped printed--Good
{
page = 1;
pages = 622374;
perpage = 1;
photo = (
{
farm = 8;
id = 27765969370;
isfamily = 0;
isfriend = 0;
ispublic = 1;
owner = "8262787#N07";
secret = 6daeee7d68;
server = 7233;
title = "Stars, Planets and Lightning Bugs";
}
);
total = 622374;
}
//wrapped and prints as optional--Good!
Optional({
page = 1;
pages = 622374;
perpage = 1;
photo = (
{
farm = 8;
id = 27765969370;
isfamily = 0;
isfriend = 0;
ispublic = 1;
owner = "8262787#N07";
secret = 6daeee7d68;
server = 7233;
title = "Stars, Planets and Lightning Bugs";
}
);
total = 622374;
})
My confusion is, if JSONData is an optional then why does it print as non-optional without ! and if it isn't an optional then why doesn't it give any error as Can not force unwrap value of non-optional type?. Since unwrapping a non-optional is error-ful!
My guess is that I am not understanding what my JSONData's type really is...
My guess is that I am not understanding what my JSONData's type really is...
I believe that is the point.
You've declared JSONData as AnyObject!, which is also known as ImplicitlyUnwrappedOptional<AnyObject>.
So, in your code print(JSONData), the value of JSONData is implicitly unwrapped.
And check the type of something in the Quick Help pane of your Xcode. It should be displayed as AnyObject?, aka Optional<AnyObject>.
One bad thing is that when implicit unwrapping occurs it doesn't get well-documented. You may need to know more about ImplicitlyUnwrappedOptional, before knowing exactly when that happens.