【发布时间】:2017-01-05 22:05:11
【问题描述】:
My tree after writing record 我写了一些记录,然后搜索相同的记录。查询时显示为空。我使用上述记录重新启动应用程序,这次我的查询找到 3 条记录。我调用 saveUserData 函数。它查询是否存在任何包含 facebookId 的记录。如果是这样,它会更新,否则它会写入新记录。由于它没有找到任何记录。它每次都会创建新记录。所以,我调用了它 3 次,所以它创造了 3 次新记录。
//new part: write User table
+(BOOL) writeOnUserWithValue:(NSMutableDictionary *)value having: (FIRDatabaseReference *)ref{
FIRDatabaseReference *newRef = [ref child:@"User"].childByAutoId;
[newRef setValue:value withCompletionBlock:^(NSError *error, FIRDatabaseReference *ref){
if(error){
NSLog(@"write on user error %@",[error description]);
}else{
NSLog(@"New Url %@",ref.URL);
[[[[ref child:@"User"] queryOrderedByChild:@"facebookId"] queryEqualToValue:value[@"facebookId"] ] observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot){
NSLog(@"Count after insert: %lu",(unsigned long)snapshot.childrenCount);
}withCancelBlock:^(NSError *error){
NSLog(@"Error found in callback query: %@",error);
}];
}
}];
return true;
}
//new part: update User table
+(BOOL) updateUserWithValue: (NSMutableDictionary *)value having: (FIRDatabaseReference *)ref with: (NSString *)key{
FIRDatabaseReference *newRef = [[ref child:@"User"] child:value[@"facebookId"]];
NSLog(@"Key: %@",key);
[newRef updateChildValues:value withCompletionBlock:^(NSError *error, FIRDatabaseReference *ref){
if(error){
NSLog(@"update on user error %@",[error description]);
}else{
NSLog(@"Update %@",ref.URL);
}
}];
return true;
}
+(BOOL) saveUserData: (NSMutableDictionary *)value having: (FIRDatabaseReference *)ref{
//FIRDatabaseReference *newRef = [ref child:@"User"];
NSLog(@"Reference URL: %@",ref.URL);
NSLog(@"Value to be saved: %@",[value description]);
[[[[ref child:@"User"] queryOrderedByChild:@"facebookId"] queryEqualToValue:value[@"facebookId"] ] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot){
if(snapshot.childrenCount==0){
NSLog(@"DO NOT EXIST");
NSLog(@"key before write: %@ %@",snapshot.key,snapshot.value);
[self writeOnUserWithValue:value having:ref];
}else{
NSLog(@"key before write: %lu %@ %@",(unsigned long)snapshot.childrenCount, snapshot.key,snapshot.value);
NSLog(@"ALREADY EXIST");
[self updateUserWithValue:value having:ref with:snapshot.key];
}
}withCancelBlock:^(NSError *error){
}];
【问题讨论】:
-
请分享您的 Firebase 数据库树。
标签: ios objective-c firebase firebase-realtime-database