firebase observeeventtype jsqmessagecollectionview avatar

时间:2017-07-25 16:54:24

标签: ios objective-c firebase firebase-authentication jsqmessagesviewcontroller

我将在对话中显示用户的头像图片。我使用了JSQMessageViewController,因此应该使用下面的函数来实现这个目标。但是,observeeventtype看起来好像没有被调用,并且有一个nil(MyuserImage或OtheruserImage)作为回报。所以会出现崩溃。那么如何在firebase中获取不同用户的照片网址,然后返回预期的头像图像?谢谢!

    - (id<JSQMessageAvatarImageDataSource>)collectionView:(JSQMessagesCollectionView *)collectionView avatarImageDataForItemAtIndexPath:(NSIndexPath *)indexPath
{
    JSQMessage *message = [self.msgArray objectAtIndex:indexPath.item];
    if([message.senderId isEqualToString:self.senderId]){
        NSString *MyuserId = [FIRAuth auth].currentUser.uid;
        __block NSString *MyuserImage;
        NSLog(@"uid is : %@",MyuserId);
        [[_photoRef child:@"users"] observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) {
            NSLog(@"My key is : %@",snapshot.key);
            if([snapshot.key isEqualToString:MyuserId]){
                NSLog(@"snapshot value is : %@", snapshot.value);
                MyuserImage = snapshot.value[@"photo"];
            }
        }];
        NSURL *url = [NSURL URLWithString:MyuserImage];
        NSData *data = [NSData dataWithContentsOfURL:url];
        self.myuserImage= [[UIImage alloc] initWithData:data];
        return [JSQMessagesAvatarImageFactory avatarImageWithImage:self.myuserImage diameter:15];
    }
    else{
        NSString *OtheruserId = message.senderId;
        __block NSString *OtheruserImage;
        NSLog(@"other userId is: %@",OtheruserId);
        [[_photoRef child:@"users"]observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot *snapshot) {
            NSLog(@"other user's key is: %@", snapshot.key);
            if([snapshot.key isEqualToString:OtheruserId]){
                NSLog(@"snapshot value is: %@", snapshot.value);
                OtheruserImage = snapshot.value[@"photo"];
            }
        }];
        NSURL *url = [NSURL URLWithString:OtheruserImage];
        NSData *data = [NSData dataWithContentsOfURL:url];
        self.otheruserImage= [[UIImage alloc] initWithData:data];
        return [JSQMessagesAvatarImageFactory avatarImageWithImage:self.otheruserImage diameter:15];
    }
}

1 个答案:

答案 0 :(得分:0)

从最好的情况我可以看出,在调用此方法之前,您需要从firebase中提取此数据。有点像创建一个与您的数据结构匹配的结构,然后能够从您的数据源中提取这些信息,这可能是您创建的这些结构的数组。

我还建议探索的一个实现是使用像SDWebImage这样的库,它将为您管理异步调用,并让您在网络请求和图像呈现发生时设置默认头像。但是在调用此方法之前,您仍然需要从数据库中获取该URL。