ios - 将 JSQMessagesViewController 与 Parse.com 一起使用

标签 ios objective-c iphone parse-platform pfobject

我遇到了一个看起来非常复杂的自定义库,它对于任何想要内置消息系统的应用程序都非常有用。JSQMessagesViewController on Github .当我试图自己实现这个库时,我遇到了一些问题。一个我不太理解“协议(protocol)”和“类”的术语(我对类有点了解)。第一个问题是我无法在 CollectionView 中使用 PFObjects,因为 JSQMessage 的实例需要通过大多数自定义方法传递。现在,我知道如何接收 PFObject 并从中获取属性,例如

self.eachMessage = [self.messages objectAtIndex:indexPath.row]; //each message
self.eachMessage[@"message"] //message from the PFObject
self.eachMessage[@"sender"] //sender from the PFObject

JSQMessage 类具有自定义属性,可以表示 PFObject 的属性,例如

JSQMessage *message = [[JSQMessage alloc] init]; //initialize it
message.senderId //could be the objectId of the user
message.senderDisplayName //the user's username
message.text //text of the message
message.date //time sent of the message

问题是,在自定义类 JSQMessage 中...所有这些属性都是只读的。我确定我可以进去更改它,以便我可以将它们分配给我想要的东西,但这里一定有我遗漏的东西。我将在我的 .h 和 .m 文件中附加所有内容。 当我发送消息时,唯一通过的是文本,我相信这是因为当来自 inputToolbar 上的 textView 时,它会被接收。

.h文件

#import <UIKit/UIKit.h>
#import <JSQMessagesViewController/JSQMessages.h>
#import <Parse/Parse.h>
#import <JSQMessagesViewController/JSQMessagesBubbleImageFactory.h>


@interface ConvoViewController : JSQMessagesViewController 

@property (strong, nonatomic) NSMutableArray *messages;
@property (strong, nonatomic) PFUser *sender;
@property (strong, nonatomic) PFUser *receiver;
@property (strong, nonatomic) JSQMessage *eachMessage;
@property (strong, nonatomic) PFObject *aMessage;
@property (strong, nonatomic) JSQMessagesBubbleImageFactory *bubbleImage;

@end

.m文件

- (void)viewDidLoad {
    [super viewDidLoad];
    //Color of the keyboard (Dark to match everything else)
    self.inputToolbar.contentView.textView.keyboardAppearance = UIKeyboardAppearanceDark;

    //Color the inputview background
    self.inputToolbar.backgroundColor = [UIColor colorWithWhite:0 alpha:0.9];

    //Delete the avatars appearing next to the messages
    self.collectionView.collectionViewLayout.incomingAvatarViewSize = CGSizeZero;
    self.collectionView.collectionViewLayout.outgoingAvatarViewSize = CGSizeZero;

    //Set the senderID
    self.senderId = self.sender.objectId;


}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:YES];

    //Query for part of the messages
    PFQuery *messages1 = [PFQuery queryWithClassName:@"Messages"];
    [messages1 whereKey:@"sender" equalTo:self.sender];
    [messages1 whereKey:@"receiver" equalTo:self.receiver];

    //Query for other part of messages
    PFQuery *messages2 = [PFQuery queryWithClassName:@"Messages"];
    [messages2 whereKey:@"sender" equalTo:self.receiver];
    [messages2 whereKey:@"receiver" equalTo:self.sender];

    //Combine those queries
    PFQuery *allMessages = [PFQuery orQueryWithSubqueries:@[messages1, messages2]];
    [allMessages findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        self.messages = [objects mutableCopy];
        [self.collectionView reloadData];
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Send Button
- (void)didPressSendButton:(UIButton *)button withMessageText:(NSString *)text senderId:(NSString *)senderId senderDisplayName:(NSString *)senderDisplayName date:(NSDate *)date {
    [JSQSystemSoundPlayer jsq_playMessageSentSound];

    JSQMessage *message = [[JSQMessage alloc] initWithSenderId:self.sender.objectId
                                             senderDisplayName:self.sender.username
                                                          date:[NSDate date]
                                                          text:text];

    [self.messages addObject:message];
    NSLog(@"%@", text);

    [self finishSendingMessageAnimated:YES];


}

#pragma mark - JSQMessages Data Source methods

- (id<JSQMessageData>)collectionView:(JSQMessagesCollectionView *)collectionView messageDataForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //Return the actual message at each indexpath.row
    return [self.messages objectAtIndex:indexPath.row];
}

- (id<JSQMessageBubbleImageDataSource>)collectionView:(JSQMessagesCollectionView *)collectionView messageBubbleImageDataForItemAtIndexPath:(NSIndexPath *)indexPath
{
    /**
     *  You may return nil here if you do not want bubbles.
     *  In this case, you should set the background color of your collection view cell's textView.
     *
     *  Otherwise, return your previously created bubble image data objects.
     */

    JSQMessage *message = [self.messages objectAtIndex:indexPath.item];
    if ([message.senderId isEqualToString:self.senderId]) {
        return [self.bubbleImage incomingMessagesBubbleImageWithColor:[UIColor orangeColor]];
    }

    return [self.bubbleImage outgoingMessagesBubbleImageWithColor:[UIColor grayColor]];
}



#pragma mark - Collection View

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    //Number of messages
    return self.messages.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    //Number of sections
    return 1;
}


- (UICollectionViewCell *)collectionView:(JSQMessagesCollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    //Creating or initial cell for the number of index paths (number of messages)
    JSQMessagesCollectionViewCell *cell = (JSQMessagesCollectionViewCell *)[super collectionView:collectionView cellForItemAtIndexPath:indexPath];

    //Put our messages dictionaries into PFObject so we can put them into individual cells
    self.eachMessage = [self.messages objectAtIndex:indexPath.row];


    //Put the message object into the textView's text property
    cell.textView.text = self.eachMessage.text;

    //Setting the text color of the message bubble based upon the sender
    if ([self.eachMessage.senderId isEqualToString:self.senderId]) {
        cell.textView.textColor = [UIColor blackColor];
    } else {
        cell.textView.textColor = [UIColor whiteColor];
    }
    //Set the top label to the person who sent the message
    cell.cellTopLabel.text = [NSString stringWithFormat:@"@%@", self.eachMessage.senderId];

    //Format the bottom label to a readable date
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM/dd/yy h:mm a"];
    cell.cellBottomLabel.text = [dateFormatter stringFromDate:self.eachMessage.date];

    //If there is a link of some sorts in the message
    cell.textView.linkTextAttributes = @{ NSForegroundColorAttributeName : cell.textView.textColor,
                                          NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle | NSUnderlinePatternSolid) };

    //What we return into the collectionview
    return cell;

}

最佳答案

这是我的部分代码。整个文件很大,如果我分享这些文件,我的老板会不高兴。 :-)

这是我在 DemoMessagesViewController 中加载 DemoData 的方式:

self.demoData = [[DemoModelData alloc] init];

self.demoData.users = @{self.senderId:self.senderDisplayName,
                        self.targetUserId:self.targetUserName};

UIImage *tempImg = [HTTPServerKaDost fetchImageFromUrlString:userProfile.profilePicUrl]; //replace with your code to load image

JSQMessagesAvatarImage *srcImage = [JSQMessagesAvatarImageFactory
                                    avatarImageWithImage:tempImg
                                    diameter:kJSQMessagesCollectionViewAvatarSizeDefault];

tempImg = [HTTPServerKaDost fetchImageFromUrlString:self.targetUserImageFullUrl];

JSQMessagesAvatarImage *destImage = [JSQMessagesAvatarImageFactory
                                     avatarImageWithImage:tempImg
                                     diameter:kJSQMessagesCollectionViewAvatarSizeDefault];

self.demoData.avatars = @{self.senderId:srcImage,
                          self.targetUserId:destImage};

[self.demoData loadMessages];

loadMessages 方法中(我在 DemoModelData 类中添加),创建 JSQMessage 对象:

JSQMessage *msg = [[JSQMessage alloc] initWithSenderId:[msgDict valueForKey:@"sender"]
                                     senderDisplayName:[msgDict valueForKey:@"fname"]
                                                  date:dateT
                                                  text:[msgDict valueForKey:@"data"]];

[self.messages addObject:msg];

任何时候你想刷新聊天 View ,在 DemoMessagesViewController 中调用它:

[self finishReceivingMessageAnimated:YES];
[self scrollToBottomAnimated:YES];

关于ios - 将 JSQMessagesViewController 与 Parse.com 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28484821/

相关文章:

ios - Match-O Linker错误,在我 friend 的Mac上构建,而不在我的Mac上构建

ios - 如何从您的 iOS 应用程序连接到后端服务器?如何读取、修改和获取数据到后端服务器?

iphone - 如何捕获UIView中CG内容的触摸事件?

iOS - 找不到右侧的配置门户选项卡

iphone - 如何使 View 像揉皱的纸一样动画

iphone - PGPlugin 类 PGBatteryLevelPlugin (pluginName : com.phonegap.battery) 不存在?

ios - 如何检查是否安装了苹果 map

iphone - UILabel 未使用另一个类的值进行更新

objective-c - 如何在 objective-c 中的双操作数中获取cos90的值

iOS 7 后台获取