I am trying to convert a FIRDataSnapshot to a custom type (i.e. I know that each child
will have a Name, Number, and Email )
When I run the code below, a JSON tree with the each child containing a Name, Number, and Email prints to the console.
So I want to store the snapshot as a custom type "PersonInfo" that has each of those properties. That way I can alter this data within my app. I need to use the "PersonInfo" variable I store this data into in various parts of my app.
ref.observeSingleEventOfType(.Value, withBlock: { (snapshot: FIRDataSnapshot) in
print(snapshot)
})
You can define a custom class PersonInfo that will act as a model.
class PersonInfo: NSObject {
var pName: String
var pNumber :String
var pEmail: String
let ref: FIRDatabaseReference?
init( name: String, number: String, email: String) {
self.pName = name
self.pNumber = number
self.pEmail = email
self.ref = nil
}
init(snapshot: FIRDataSnapshot) {
pName = snapshot.value!["pName"] as! String
pNumber = snapshot.value!["pNumber"] as! String
pEmail = snapshot.value!["pEmail"] as! String
ref = snapshot.ref
}
convenience override init() {
self.init(name:"",number: "", email: "")
}
}
And inside your observeSingleEventOfType
when you have snapshot
, you can iterate over its children and fetch each Person as:
for item in snapshot.children{
var person = PersonInfo(snapshot:item);
yourList.append(person);
}
So, you will have a list of PersonInfo
model objects that you can access later.
In objective c you can do so :
Header file :
#import <Foundation/Foundation.h>
#import <FirebaseDatabase/FirebaseDatabase.h>
@interface RTAObject : NSObject
@property (nonatomic) NSString pName;
@property (nonatomic) NSString * pNumber;
@property (nonatomic) NSString * pEmail;
-(id) init:(NSString) pName : (NSString*) name :(NSString*) pNumber :(NSString*) pEmail ;
@end
Source File :
#import "PersonInfo.h"
@implementation RTAObject
-(id)init:(FIRDataSnapshot *)snapshot {
_pName = [snapshot valueForKey:@"name"];
_pNumber = [snapshot valueForKey:@"number"];
_pEmail = [snapshot valueForKey:@"email"];
return self;
}
-(id) init:(NSString *)pName:(NSString *)pNumber :(NSString *)pEmail
{
_pName = pName;
_pNumber = pNumber;
_pEmail = pEmail;
return self;
}
@end