iosfirebaseblocknsuinteger

Use Variable outside Firebase Block


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?


Solution

  • 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
    }