Hi I am trying to retrieve data from the firebase database. Here is my code
- (FIRDatabaseReference *) referenceFromURL:(NSString *)databaseUrl{
commentsRef = [[FIRDatabase database] referenceFromURL:databaseUrl];
return commentsRef;
}
-(void)viewWillAppear:(BOOL)animated
{
[commentsRef
observeEventType:FIRDataEventTypeValue
withBlock:^(FIRDataSnapshot *snapshot) {
NSDictionary * post = snapshot.value;
}];
}
The reference is successfully built by the database but the code written in block
"NSDictionary * post = snapshot.value;"
didn't execute.
You can do it easily. If you want to fetch all info using this you can do this. Make sure you have made your db public
#property (strong, nonatomic) FIRDatabaseReference *ref;
Define Property on interface then
self.ref = [[FIRDatabase database] reference];
[self.ref observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
NSDictionary *usersDict = snapshot.value;
NSLog(#"Information : %#",usersDict);
}];
If you want to fetch specific portion using this you can do this
[[self.ref child:#"results"] observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
NSDictionary *usersDict = snapshot.value;
NSLog(#"Info : %#",usersDict);
}];
My Fetched Json From Firebase
{
"results" : [
{
"name":"test 1",
"URL" : "URL STRING"
},
{
"name":"test 1",
"URL" : "URL STRING"
},
{
"name":"test 1",
"URL" : "URL STRING"
},
{
"name":"test 1",
"URL" : "URL STRING"
}
]
}
Will be cool if you can update to firebase 3.0.
If you want to take a look to MakinGIANST - Post about firebase to get more info about how to query and use the new api.
It's for Android but its in Kotlin so will look like Swift
Related
I'm newbie with Firebase. I try to get data in Database, but my code is not working. Here is my code:
- (void) getData{
FIRDatabaseReference *ref = [[FIRDatabase database] reference];
//READ DATA
[[[ref child:#"buysell"] child:#"users"] observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
NSDictionary *dict = snapshot.value;
NSLog(#"%#",dict);
} withCancelBlock:^(NSError * _Nonnull error) {
}];
}
It cant jump in withBlock:^(FIRDataSnapshot * _Nonnull snapshot). What seems to be wrong? Please help me. Thanks.
Move this to viewDidLoad
FIRDatabaseReference *ref = [[FIRDatabase database] reference];
Check whether you configured everything according to the documentation.
Check the key names
If everything is fine then try changing this
Try with observeSingleEventOfType instead of observeEventType
[[[self.ref child:#"buysell"] child:#"users"] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
NSDictionary *dict = snapshot.value;
NSLog(#"%#",dict);
} withCancelBlock:^(NSError * _Nonnull error) {
NSLog(#"%#", error.localizedDescription);
}];
If above 3 not works check your error statement
You can do it easily. If you want to fetch all info using this you can do this. Make sure your db is public
#property (strong, nonatomic) FIRDatabaseReference *ref;
Define Property on interface then
self.ref = [[FIRDatabase database] reference];
[self.ref observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
NSDictionary *usersDict = snapshot.value;
NSLog(#"Information : %#",usersDict);
}];
If you want to fetch specific portion using this you can do this
[[self.ref child:#"results"] observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
NSDictionary *usersDict = snapshot.value;
NSLog(#"Info : %#",usersDict);
}];
My Fetched Json From Firebase
{
"results" : [
{
"name":"test 1",
"URL" : "URL STRING"
},
{
"name":"test 1",
"URL" : "URL STRING"
},
{
"name":"test 1",
"URL" : "URL STRING"
},
{
"name":"test 1",
"URL" : "URL STRING"
}
]
}
At the moment I have an app that is using Firebase database to store the users:
Name
School
Subject
Within three separate textfields.
Right now I've managed to allow the user to enter his details within these three text fields and hit a button labeled update, which then sends the data to my firebase console.
This means that the user can enter their details, hit update and see them while they are logged in. however as soon as they logout and login again the textfields are blank, despite the fact that firebase has the info stored on its server.
I've been playing around all day trying to get it to work but to no avail.
Here we have the firebase reference and auth:
self.rootRef = [[FIRDatabase database] reference];
self.user = [FIRAuth auth].currentUser;
And the update button code that sends the users info to the firebase database:
- (IBAction)didTapEditProfile:(id)sender {
if (![_textFieldOne.text isEqual: #""]) {
NSString *item = _textFieldOne.text;
[[[[_rootRef child:#"users"] child:_user.uid] child:#"Name"] setValue:item];
}
if (![_textFieldTwo.text isEqual: #""]) {
NSString *itemTwo = _textFieldTwo.text;
[[[[_rootRef child:#"users"] child:_user.uid] child:#"School"] setValue:itemTwo];
}
if (![_textFieldThree.text isEqual: #""]) {
NSString *itemThree = _textFieldThree.text;
[[[[_rootRef child:#"users"] child:_user.uid] child:#"Subject"] setValue:itemThree];
}
}
The problem i'm having is with retrieving the data within the code below which is situated in the viewDidAppear:
[[_rootRef child:#"users"] observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
NSDictionary *usersDict = snapshot.value;
NSLog(#"%#",usersDict);
[usersDict objectForKey:_user.uid];
//I've tried numerous solutions here to get the text fields to display the info from the database
mainly:
NSString *field;
field = _textFieldOne.text;
field = [userDict objectForKey #"Name"];
The code i'm attempting to translate from looks like this:
field(userDict?.objectForKey("Name") as? String)
}];
Any ideas?
I managed to get everything sorted as follows:
-(void)configure:(NSString *)field {
_textFieldOne.text = field;
}
and then within the code I was having the problem:
[[_rootRef child:#"users"] observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
NSDictionary *usersDict = snapshot.value;
NSLog(#"%#",usersDict);
[usersDict objectForKey:_user.uid];
[self configure:[userDict objectForKey:#"Name"]];
}];
Thanks for the help.
Hey Joshua I have implemented the firebase and successfully retrieve the data from the firebase but the problem is i have implemented that in swift... here is my actual code if this helps you......
**rootRef.queryOrderedByChild("search what you want like specific name etc etc").observeEventType(.ChildAdded, withBlock: { snapshot in
if snapshot.value is NSNull {
print("the chat model is null")
SVProgressHUD.dismiss()
SVProgressHUD.showErrorWithStatus("No messages")
}
else {
print(snapshot) }**
Or if you want to fetch the whole database JSON here is the query
**rootref.observeEventType(.ChildAdded) { (snapshot: FDataSnapshot!) in
// 3
let id = snapshot.value["senderId"] as! String
let text = snapshot.value["text"] as! String
// 4
self.addMessage(id, text: text)
// 5
self.finishReceivingMessage()
}**
Here is a nice tutorial on this
https://www.raywenderlich.com/122148/firebase-tutorial-real-time-chat
If you want this to convert in objective-c then of course I will help you
I'm trying to retrieve data from firebase and I an using the guide given by firebase but I am not able to create the reference with my firebase database.
FIRDatabaseReference * ref = [[FIRDatabase alloc]
referenceFromURL:#"https://project-8326407164650950213.firebaseio.com"];
NSLog(#"%#",ref);
I am using this code to create the reference with my database but app crash.
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** setObjectForKey: key cannot be nil'
I am new in iOS and first time using firebase. Please tell me the solution as I am going according to firebase guide.
I'm no firebase expert, but when you're working with a class in Obj-C, you'll either invoke its class methods (e.g. [FIRDatabase database]), or you'll first allocate and initialize it ([[FIRDatabase alloc] <an initializer>]), and secondly use an instance method on the instance.
In your code sample above, I see an alloc without an initializer, which makes me think you're missing something.
If I look at the iOS quick start, I see a call to initWithURL, which is one of the initializers.
Firebase *messagePath = [[Firebase alloc] initWithUrl:[NSString stringWithFormat:#"%#%#%#", MAIN_URL,MESSAGES_DIRECTORY,conversationId]];
[[messagePath queryLimitedToLast:10] observeEventType:FEventTypeChildAdded withBlock:^(FDataSnapshot *snapshot) {
NSMutableArray *messages = [[NSMutableArray alloc] init];
[messages addObject:snapshot.value];
observingBlock(true,messages);
}];
Here is the code with you can get the data and value of the node. First make url till your node.
Still you have any problem just add comment here. now a days working on Firebase chat in swift.
You can do it easily. If you want to fetch all info using this you can do this. Make sure you have made your db public then no auth needed
#property (strong, nonatomic) FIRDatabaseReference *ref;
Define Property on interface then
self.ref = [[FIRDatabase database] reference];
[self.ref observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
NSDictionary *usersDict = snapshot.value;
NSLog(#"Information : %#",usersDict);
}];
If you want to fetch specific portion using this you can do this
[[self.ref child:#"results"] observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
NSDictionary *usersDict = snapshot.value;
NSLog(#"Info : %#",usersDict);
}];
My Fetched Json From Firebase
{
"results" : [
{
"name":"test 1",
"URL" : "URL STRING"
},
{
"name":"test 1",
"URL" : "URL STRING"
},
{
"name":"test 1",
"URL" : "URL STRING"
},
{
"name":"test 1",
"URL" : "URL STRING"
}
]
}
I cant seem to retrieve any information from my firebase database. I created a table with both author and title available.
This is the code i ran in my ios app, but the app just keeps crashing.
// Get a reference to our posts
Firebase *ref = [[Firebase alloc] initWithUrl: #"**********"];
[ref observeEventType:FEventTypeChildAdded withBlock:^(FDataSnapshot *snapshot) {
NSLog(#"%#", snapshot.value[#"author"]);
NSLog(#"%#", snapshot.value[#"title"]);
}];
}
I cant tell whats going wrong, any help with this i will be appreciated.
Thank you
change event type to
[ref observeEventType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {
NSLog(#"%#", snapshot.value[#"author"]);
NSLog(#"%#", snapshot.value[#"title"]);
}];
You would generally not store data like that right under your root node - it would generally be a child node(s) stored under the root node, like this:
sizzling-inferno-255
book_node_0
author: test_author
title: test title
book_node_1
author: another author
title: another title title
Firebase *ref = [[Firebase alloc] initWithUrl: #"sizzling-inferno-255"];
[ref observeEventType:FEventTypeChildAdded withBlock:^(FDataSnapshot *snapshot) {
NSLog(#"%#", snapshot.value[#"author"]);
NSLog(#"%#", snapshot.value[#"title"]);
}];
will iterate over each book node and return a snapshot of that node. So the first time a snapshot is returned, it will be
book_node_0
author: test_author
title: test title
and the second time a snapshot is returned will be
book_node_1
author: another author
title: another title title
the book_node keys are generated with childByAutoId.
ChildAdded reads in each child node one at a time as a snapshot.
Value reads in everything in the node; all child nodes, those children etc and can be a large amount of data. If the ref node contains children, like in this answer, all of the nodes are returned and they need to be iterated over to get the child data, so within the observe block...
for child in snapshot.children {
NSLog(#"%#", child.value[#"author"]);
}
Edit - and to specifically answer the OP question, here's how you do it with the Firebase structure in the question:
self.myRootRef = [[Firebase alloc] initWithUrl:#"https://**********"];
[ref observeEventType:FEventTypeChildAdded withBlock:^(FDataSnapshot *snapshot) {
NSString *key = snapshot.key;
NSString *value = snapshot.value;
if ( [key isEqualToString:#"author"] ) {
NSLog(#"author = %#", value);
} else if ([snapshot.key isEqualToString:#"title"] ) {
NSLog(#"title = %#", value);
}
}];
I managed to get the user likes using this code:
[FBRequestConnection startWithGraphPath:#"/me/likes"
parameters:nil
HTTPMethod:#"GET"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
/* handle the result */
NSLog(#"User interests data: %#",result);
self.likesTextView.text = [NSString stringWithFormat:#"User interests data: %#",result];
}];
This is the log:
User interests data: {
data = (
{
category = Company;
"created_time" = "2015-04-09T11:31:13+0000";
id = 403422586500762;
name = "Sky3888 iOS & Android - Officially Agent";
},
{
category = "Games/toys";
"created_time" = "2015-04-09T11:30:57+0000";
id = 1575053229378162;
name = i12win;
},
{
category = "Shopping/retail";
"created_time" = "2015-04-07T04:44:09+0000";
id = 273182176129865;
name = Tinkerbelle;
}
);
However how do I get and display the "name" and "category" field in a UILabel?
You can do as below
NSDictionary *responseDict=(NSDictionary *)result;
NSArray *mainArray=[responseDict objectForKey:#"data"];
for (NSDictionary *dict in mainArray) {
nameLabel.text=[dict valueForKey:#"name"];
catLabel.text=[dict valueForKey:#"category"];
}
Hope it helps you..!
Make an NSArray of the result and then loop through the objects in it performing the function objectForKeyon category and name to extract the data you want.
There is a similar question answered here:
NSMutableArray losing all objects
You should be able to use the code from that and copy the results into your UILabel.