Objective-C - Firebase 从数据库中检索数据并填充到表中

Posted

技术标签:

【中文标题】Objective-C - Firebase 从数据库中检索数据并填充到表中【英文标题】:Objective-C - Firebase retrieving data from database and populate in table 【发布时间】:2016-08-01 05:22:55 【问题描述】:

Database structure

我有一个 Firebase 数据库设置(请参考图片)。

我有一个“FeedViewController”来显示数据库中每个帖子的内容。用户可以发布一个或多个帖子。

从 Firebase 快照中检索这些帖子并将它们存储到字典中时,我发现在 Firebase 的 observeEventType 函数之外无法访问该字典的值。

我的想法是检索这些键值对,将它们存储到 NSObject 自定义类对象(Post *post)中,并使用该对象为我的“FeedViewController”加载表格视图。在 observeEventType 函数内部,我可以访问对象的值,但在外部,我不能。结果,我不知道如何使用这些值来填充我的 FeedViewController 中的表格视图。我知道这个 observeEventType 函数是一个异步回调,但我不知道如何访问对象的值并填充我的表。我不知道 dispatch_async(dispatch_get_main_queue() 函数在这里做什么。任何帮助将不胜感激。谢谢!

FeedViewController.m

#import "FeedViewController.h"
#import "Post.h"
#import "BackgroundLayer.h"
#import "SimpleTableCell.h"
#import "FBSDKCoreKit/FBSDKCoreKit.h"
#import "FBSDKLoginKit/FBSDKLoginKit.h"
#import "FBSDKCoreKit/FBSDKGraphRequest.h"
@import Firebase;
@import FirebaseAuth;
@import FirebaseStorage;
@import FirebaseDatabase;

@interface FeedViewController()

@property (strong, nonatomic) Post *post;

@end

@implementation FeedViewController

-(void) viewDidLoad 

[super viewDidLoad];

_ref = [[FIRDatabase database] reference];

self.post = [[Post alloc] init];

/*

_idArr = [[NSMutableArray alloc] init];


_postDict = [[NSMutableDictionary alloc] init];
_idDict = [[NSMutableDictionary alloc] init];
_postID = [[NSMutableArray alloc] init];

_userName = [[NSMutableArray alloc] init];
_placeName = [[NSMutableArray alloc] init];
_addressLine1 = [[NSMutableArray alloc] init];
_addressLine2 = [[NSMutableArray alloc] init];
_ratings = [[NSMutableArray alloc] init];
_desc = [[NSMutableArray alloc] init];
_userEmail = [[NSMutableArray alloc] init];
_userIDArray = [[NSMutableArray alloc] init];
 */
[self fetchData];

 NSLog(@"Emails: %@", _post.userID);




-(void) viewWillAppear:(BOOL)animated 

[super viewWillAppear:animated];

CAGradientLayer *bgLayer = [BackgroundLayer blueGradient];
bgLayer.frame = self.view.bounds;
[self.view.layer insertSublayer:bgLayer atIndex:0];

FIRUser *user = [FIRAuth auth].currentUser;

if (user != nil)

    //fbFirstName.text = user.displayName;
    //fbEmail.text = user.email;
    NSURL *photoUrl = user.photoURL;
    NSString *userID = user.uid;
    //NSString *uploadPath = [userID stringByAppendingString:@"/profile_pic.jpg"];
    //NSData *data = [NSData dataWithContentsOfURL:photoUrl];
    //ProfilePic.image = [UIImage imageWithData:data];

    FIRStorage *storage = [FIRStorage storage];
    FIRStorageReference *storageRef = [storage referenceForURL:@"gs://foodsteps-cee33.appspot.com"];

    NSString *access_token = [[NSUserDefaults standardUserDefaults] objectForKey:@"fb_token"];

    FBSDKGraphRequest *friendList = [[FBSDKGraphRequest alloc]
                                  initWithGraphpath:@"me?fields=friends"
                                parameters:nil
                                  tokenString: access_token
                                  version:nil
                                  HTTPMethod:@"GET"];

    [friendList startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
                                          id result,
                                          NSError *error) 

        if(error == nil)
        
            //NSLog(@"%@", result);
            NSDictionary *dictionary = (NSDictionary *)result;
            NSDictionary *dict = [dictionary objectForKey:@"friends"];

            _idArray = [[NSMutableArray alloc] init];

            for(int i = 0; i < [[dict objectForKey:@"data"] count]; i++) 

                [_idArray addObject:[[[dict objectForKey:@"data"] objectAtIndex:i] valueForKey:@"id"]];
            

            //NSLog(@"%@", idArray);
        

        else 
            NSLog(@"%@",error);
        
    ];





-(void) fetchData 

_refHandle = [[_ref child:@"users"]     observeEventType:FIRDataEventTypeValue
                                           withBlock:^(FIRDataSnapshot * _Nonnull snapshot)
              
                  NSDictionary *postDict = snapshot.value;
                  NSLog(@"%@", postDict);

                  for( NSString *aKey in [postDict allKeys] )
                  
                      // do something like a log:
                      _post.userID = aKey;
                  

                  //_post.
                  //[_post setValuesForKeysWithDictionary:postDict];
                  [self.tableView reloadData];

            ];

NSLog(@"Emails: %@", _post.userID);

dispatch_async(dispatch_get_main_queue(), ^

[self.tableView reloadData];

);


-(void) viewWillDisappear:(BOOL)animated

    [super viewWillDisappear:animated];
    [[_ref child:@"users"] removeObserverWithHandle:_refHandle];


@end

Post.m

#import "Post.h"

@implementation Post


- (instancetype)init 

return [self initWithUid:@""
               andPostid:@""
             andUsername:@""
                 andDesc:@""
              andRatings:@""
            andPlacename:@""
         andAddressLine1:@""
         andAddressLine2:@""
                andEmail:@""];


- (instancetype)initWithUid:(NSString *)userID
            andPostid:(NSString *)postID 
andUsername: (NSString *)userName
andDesc:(NSString *)desc
andRatings:(NSString *)ratings
andPlacename: (NSString *)placeName
andAddressLine1: (NSString *)addressLine1
andAddressLine2: (NSString *)addressLine2
andEmail: (NSString *)userEmail 

self = [super init];
if(self) 
    self.userID = userID;
    self.postID = postID;
    self.userName = userName;
    self.desc = desc;
    self.ratings = ratings;
    self.placeName = placeName;
    self.addressLine1 = addressLine1;
    self.addressLine2 = addressLine2;
    self.userEmail = userEmail;


return self;


@end

【问题讨论】:

【参考方案1】:

你的方法是我最初尝试做的。但是我在 cellforrowatindexpath 中访问它时遇到了问题。对我有用的是。

- (void)configureDatabase :(NSUInteger)postsAmount

_ref = [[FIRDatabase database] reference];
// Listen for new messages in the Firebase database
_refHandle = [[[[_ref child:@"posts"]queryOrderedByKey] queryLimitedToLast:postsAmount]observeEventType:FIRDataEventTypeChildAdded withBlock:^(FIRDataSnapshot *snapshot) 

        [_posts insertObject:snapshot atIndex:0];
   ];

然后在viewdid出现

        [self configureDatabase:_numberOfPosts];

最后

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath


FIRDataSnapshot *postsSnapshot = _posts[indexPath.section];

NSDictionary *post = postsSnapshot.value;
//use key values to create your views.

还包括

@property (strong, nonatomic) NSMutableArray<FIRDataSnapshot *> *posts;

它的作用是在 firebase 中查询您的值并接收快照。然后将这些快照放在您的 _posts 数组中,然后您可以通过其他方法访问它们。

【讨论】:

以上是关于Objective-C - Firebase 从数据库中检索数据并填充到表中的主要内容,如果未能解决你的问题,请参考以下文章

Firebase:混合 C++ 和 Objective-C SDK 可以吗?

Objective-C - Firebase 从数据库中检索数据并填充到表中

从 firebase 数据库中检索数据并在 Objective-C 中的 UITable 中显示

如何在 Firestore Objective-c 上设置/更新数据时以秒为单位获取 Firebase 服务器时间?

Xcode 11.4 Objective-C 语言的快速帮助,而不是 swift 语言,用于带有 Cocoapods 的 firebase API(iOS 13.4 应用程序)

用筛选法可得到2~n(n<10000)之间的所有素数,方法是:首先从素数2开始,将所有2的倍数的数从数表中删去(把数表中相应位置的值置成0);接着从数表中找出下一个非0数,并从数表中删去该倍数的