Use Variable outside Firebase Block

82 Views Asked by At

Hello everyone I'm using Firebase for my ios project ... I have a lot of trouble using the values of my variables outside of the Firebase blocks when I query the database.

For example in this case I'm trying to get a number value from this query ...

 FIRDatabaseReference *userDbRef = FIRDatabase.database.reference;
 [[[userDbRef child:RTDUSER] child:userID] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {

     NSUInteger totalCFU = [snapshot.value[RTDUSER_TOTALCFU] unsignedIntegerValue];

} withCancelBlock:nil];

I need this number value also obtained outside the block (in other functions of this class) ...

How can I use the TotalCFU variable outside the firebase block?

2

There are 2 best solutions below

5
picciano On BEST ANSWER

You can call a method from inside the block to handle the value.

FIRDatabaseReference *userDbRef = FIRDatabase.database.reference;
 [[[userDbRef child:RTDUSER] child:userID] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {

    NSUInteger totalCFU = [snapshot.value[RTDUSER_TOTALCFU] unsignedIntegerValue];

    // Call a function to handle value
    [self doSomethingWithCFU: totalCFU];

} withCancelBlock:nil];

Somewhere else in your class:

(void)doSomethingWithCFU:(NSUInteger)totalCFU {
    // Do something with the value
}
0
badhanganesh On

Use __block to use your variable outside.

FIRDatabaseReference *userDbRef = FIRDatabase.database.reference;
__block NSUInteger totalCF;
[[[userDbRef child:RTDUSER] child:userID] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {

     totalCFU = [snapshot.value[RTDUSER_TOTALCFU] unsignedIntegerValue];

} withCancelBlock:nil];