我将用户邮政编码保存到Firebase数据库,并希望在应用启动时查询该数据库,以查看用户是否已输入其邮政编码,或者他们是否是新用户。< / p>
我之前发过我的代码。我从Firebase文档中提取了示例代码,但似乎我的应用程序甚至从未运行以下代码来获取值
[[[_ref child:@"user"] child:userID] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {...
我错过了什么?
#import "FollowingVC.h"
#import <FirebaseDatabase/FirebaseDatabase.h>
@import Firebase;
@interface FollowingVC ()
@property NSString *uid;
@property FIRDatabaseReference *ref;
@property NSString *zipcode;
@end
@implementation FollowingVC
- (void)viewDidLoad {
[super viewDidLoad];
[self createAuthorizedUser];
[self checkForZipCode];
}
-(void)createAuthorizedUser
{
[[FIRAuth auth]
signInAnonymouslyWithCompletion:^(FIRUser *_Nullable user, NSError *_Nullable error) {
if (!error) {
self.uid = user.uid;
self.ref=[[FIRDatabase database]reference];
}
}];
}
-(void)checkForZipCode
{
NSString *userID = [FIRAuth auth].currentUser.uid;
[[[_ref child:@"user"] child:userID] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
// Get user value
self.zipcode = snapshot.value[@"zip code"];
NSLog(@"It worked: %@", self.zipcode);
// ...
} withCancelBlock:^(NSError * _Nonnull error) {
NSLog(@"%@", error.localizedDescription);
}];
}
@end
答案 0 :(得分:1)
Firebase是异步的,您需要留出时间让事件完成,然后才能在应用中继续播放。
在这种情况下,您应该在填充self.uid之后在登录块内调用[self checkForZipCode]。
否则,在填充self.uid之前,您将面临运行checkForZipCode函数的风险。
让Firebase控制应用程序的流程 - 并且不要尝试同步使用Firebase,因为它会因为互联网滞后等而让您陷入困境。