【问题标题】:Objective-C - Firebase retrieving data from database and populate in tableObjective-C - Firebase 从数据库中检索数据并填充到表中
【发布时间】: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

【问题讨论】:

    标签: ios objective-c firebase firebase-realtime-database


    【解决方案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 数组中,然后您可以通过其他方法访问它们。

    【讨论】:

      猜你喜欢
      • 2019-06-15
      • 1970-01-01
      • 1970-01-01
      • 2011-05-29
      • 1970-01-01
      • 2013-03-17
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      相关资源
      最近更新 更多