Gibraltar Gibraltar - 3 months ago 33
iOS Question

How to save child value in Firebase using Objective-C

I'm trying to use Firebase to save a small amount of user data in an app I'm working on. I'd like to save the users zip code (which they'll enter) and then let them choose to follow certain topics.

I currently have the zip code being saved, but I can't get the child data to save correctly.

Can anyone help point out what I need to add next to allow child data to be saved off of a users zip code?

#import "ZipCodeVC.h"
#import <FirebaseStorage/FirebaseStorage.h>
#import <FirebaseDatabase/FirebaseDatabase.h>

@interface ZipCodeVC ()

@property FIRDatabaseReference *ref;

@end

@implementation ZipCodeVC

- (void)viewDidLoad {
[super viewDidLoad];

self.ref=[[FIRDatabase database]reference];
[[self.ref child:@"Zip Code"] setValue:@"61354"];

}


@end

Answer

Figured it out!

#import "ZipCodeVC.h"
#import <FirebaseStorage/FirebaseStorage.h>
#import <FirebaseDatabase/FirebaseDatabase.h>
@import Firebase;

@interface ZipCodeVC ()

@property NSString *uid;
@property (strong, nonatomic) IBOutlet UITextField *zipcodeTextField;

@property FIRDatabaseReference *ref;

@end

@implementation ZipCodeVC

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (IBAction)tappedSubmit:(id)sender
{
    [[FIRAuth auth]
     signInAnonymouslyWithCompletion:^(FIRUser *_Nullable user, NSError *_Nullable error) {
         if (!error) {
             self.uid = user.uid;

             self.ref=[[FIRDatabase database]reference];
             //[[self.ref child:@"User ID"] setValue:uid]; old code that worked for creating main value

             [self writeNewPost:self.uid zipcode:self.zipcodeTextField.text title:@"Test Title" body:@"Body"];

         }
     }];
}


- (void)writeNewPost:(NSString *)userID zipcode:(NSString *)zipcode title:(NSString *)title body:(NSString *)body
{
    NSString *key = self.uid;

    NSDictionary *post = @{@"uid": userID,
                           @"zip code": zipcode,
                           @"title": title,
                           @"body": body};
    NSDictionary *childUpdates = @{[NSString stringWithFormat:@"/user/%@", key]: post};

    [_ref updateChildValues:childUpdates];
}


@end
Comments