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

时间:2016-08-01 05:22:55

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

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 个答案:

答案 0 :(得分: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];
   }];
}

然后在viewdidappear

        [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数组中,然后您可以使用其他方法访问它们。