Force asynchrounous Firebase query to execute synchronously?

ぃ、小莉子 提交于 2019-12-17 21:35:30

问题


I'm designing an app that uses firebase to store user information. Below, I'm trying to write a method that queries the database, obtains the stored password, and checks it against the inputted password, returning a boolean based on whether or not they match.

-(BOOL) ValidateUser: (NSString*)username :(NSString*)password {


//initialize blockmutable true-false flag
__block bool loginFlag = true;

//initialize blockmutable password holder
__block NSString* passholder;

//check if user exists in database
//get ref to firebase
Firebase * ref = [[Firebase alloc] initWithUrl:kFirebaseURL];

//delve into users
Firebase * usersref = [ref childByAppendingPath:@"users"];

//search based on username
FQuery * queryRef = [[usersref queryOrderedByKey] queryEqualToValue: username];

//EXECUTION SKIPS THIS PORTION OF CODE
//get snapshot of things found
[queryRef observeEventType:FEventTypeChildAdded withBlock:^(FDataSnapshot *querySnapshot){
    NSLog(@"%@", querySnapshot);

    if no match found
    if (querySnapshot.childrenCount == 0)
    {
        return false
        loginFlag = false;
    }

    //otherwise store password of thing found
    else
    {
        passholder = querySnapshot.value[@"hashed_password"];
        NSLog(@"%@", passholder);
    }

}];

//CODE SKIPS TO HERE

NSLog(@"%@", passholder);

//check inputted password against database password
if (![password isEqualToString:passholder])
{
    //if they don't match, return false
    loginFlag = false;
}

return loginFlag;
}

The problem, however, is that the method terminates and returns true before the firebase query runs. Essentially, the method executes, checks placeholder values against the inputted password, returns the value for the bool, AND ONLY THEN retrieves the password(within the block). I'm not sure how to force the block to run synchronously in order to actually return the correct boolean.

Is there any way to alter the flow of the method in order to actually have it return the correct boolean value? I'm at a loss.

Thanks so much

PS: I'm aware that Firebase supports a dedicated login functionailty (AuthUser and all that); however, this project is more of a proof of concept and so we're utilizing simple, unencrypted passwords stored in the main firebase.


回答1:


To force your function to wait for some asynchronous action to complete, check out semaphores. Here's another StackOverflow question which tackles it: objective c - How do I wait for an asynchronously dispatched block to finish?



来源:https://stackoverflow.com/questions/27338575/force-asynchrounous-firebase-query-to-execute-synchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!