2016-08-29 4 views
0

私は、ユーザーの郵便番号をFirebaseデータベースに保存しています。そのデータベースをアプリの起動時に照会して、ユーザーが郵便番号を既に入力しているかどうか、まったく新しいユーザーであるかどうかを確認します。Obj-Cを使用してFirebaseからデータポイントを取得する方法は?

前にコードを投稿しました。私は私が上で何を逃しています

[[[_ref child:@"user"] child:userID] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {... 

Firebaseドキュメントからのサンプルコードを引っ張ったが、それは値を取得するために私のアプリでも、次のコードを実行されることはありませんようだ

#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 

答えて

1

Firebaseは非同期であり、イベントが完了するまでに時間がかかる必要があります。

この場合、self.uidが入力された後で、サインインブロック内で[self checkForZipCode]を呼び出す必要があります。

そうしないと、self.uidが読み込まれる前にcheckForZipCode関数が実行される危険性があります。

Firebaseがアプリケーションの流れを制御し、インターネットの遅れなどのためにFirebaseを同期的に使用しようとしないでください。

関連する問題