每当我在对话框中发送或接收消息(它们都是public_group类型)时,它都不会更新,直到我解除DialogViewController并再次打开它。这是代码:
static NSString *ChatMessageCellIdentifier = @"ChatMessageCellIdentifier";
@interface DialogViewController () <ChatServiceDelegate,QBChatDelegate, QMChatServiceDelegate, UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, weak) IBOutlet UITextField *messageTextField;
@property (nonatomic, weak) IBOutlet UIButton *sendMessageButton;
@property (nonatomic, weak) IBOutlet UIView *inputBackgroundView;
@property (nonatomic, weak) IBOutlet UITableView *tableView;
@property (nonatomic, assign) BOOL isKeyboradShow;
@property (nonatomic, strong) UIRefreshControl *refreshControl;
@property (nonatomic, strong) NSMutableArray *messageArray;
- (IBAction)sendMessage:(id)sender;
@end
@implementation DialogViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.messageArray = [NSMutableArray array];
[[QBChat instance] addDelegate:self];
[[QBChat instance] setAutoReconnectEnabled:YES];
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
[self.view addGestureRecognizer:gestureRecognizer];
// Initialize the refresh control.
self.refreshControl = [[UIRefreshControl alloc] init];
self.refreshControl.backgroundColor = [UIColor whiteColor];
[self.refreshControl addTarget:self
action:@selector(getPreviousMessages)
forControlEvents:UIControlEventValueChanged];
[self.tableView addSubview:self.refreshControl];
//Gesture
/* UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(messageTextFieldDidTap:)];
[self.messageTextField addGestureRecognizer:tapGesture];
*/
//Table view cells
[self.tableView registerClass:[ChatMessageTableViewCell class] forCellReuseIdentifier:ChatMessageCellIdentifier];
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
NSLog(@"chat: %@", self.dialog);
// Set keyboard notifications
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification object:nil];
[ChatService shared].delegate = self;
self.messageArray = [NSMutableArray arrayWithArray:[[ChatService shared] messagsForDialogId:self.dialog.ID]];
// Set title
if(self.dialog.type == QBChatDialogTypePrivate){
QBUUser *recipient = [ChatService shared].usersAsDictionary[@(self.dialog.recipientID)];
self.title = recipient.login == nil ? recipient.email : recipient.login;
}else{
self.title = self.dialog.name;
}
// sync messages history
//
[self syncMessages:NO];
}
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[ChatService shared].delegate = nil;
}
-(BOOL)hidesBottomBarWhenPushed
{
return YES;
}
- (void)getPreviousMessages{
// load more messages here
//
[self syncMessages:YES];
}
- (void)syncMessages:(BOOL)loadPrevious{
NSArray *messages = [[ChatService shared] messagsForDialogId:self.dialog.ID];
NSDate *lastMessageDateSent = nil;
NSDate *firstMessageDateSent = nil;
if(messages.count > 0){
lastMessageDateSent = ((QBChatMessage *)[messages lastObject]).dateSent;
firstMessageDateSent = ((QBChatMessage *)[messages firstObject]).dateSent;
}
NSMutableDictionary *extendedRequest = [[NSMutableDictionary alloc] init];
if(loadPrevious){
if(firstMessageDateSent != nil){
extendedRequest[@"date_sent[lte]"] = @([firstMessageDateSent timeIntervalSince1970]-1);
}
}else{
if(lastMessageDateSent != nil){
extendedRequest[@"date_sent[gte]"] = @([lastMessageDateSent timeIntervalSince1970]+1);
}
}
extendedRequest[@"sort_desc"] = @"date_sent";
QBResponsePage *page = [QBResponsePage responsePageWithLimit:100 skip:0];
[QBRequest messagesWithDialogID:self.dialog.ID
extendedRequest:extendedRequest
forPage:page
successBlock:^(QBResponse *response, NSArray *messages, QBResponsePage *page) {
if(messages.count > 0){
[[ChatService shared] addMessages:messages forDialogId:self.dialog.ID];
NSLog(@"messages in request: %lu", messages.count);
}
if(loadPrevious){
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMM d, h:mm a"];
NSString *title = [NSString stringWithFormat:@"Last update: %@", [formatter stringFromDate:[NSDate date]]];
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:[UIColor blackColor]
forKey:NSForegroundColorAttributeName];
NSAttributedString *attributedTitle = [[NSAttributedString alloc] initWithString:title attributes:attrsDictionary];
self.refreshControl.attributedTitle = attributedTitle;
[self.refreshControl endRefreshing];
[self.tableView reloadData];
}else{
[self.tableView reloadData];
NSInteger count = [[ChatService shared] messagsForDialogId:self.dialog.ID].count;
if(count > 0){
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:count-1 inSection:0]
atScrollPosition:UITableViewScrollPositionBottom animated:NO];
}
}
} errorBlock:^(QBResponse *response) {
}];
}
#pragma mark
#pragma mark Actions
- (IBAction)sendMessage:(id)sender{
NSString *messageText = self.messageTextField.text;
if(messageText.length == 0){
return;
}
QBChatMessage *message = [QBChatMessage message];
message.text = messageText;
message.markable = YES;
message.dialogID = self.dialog.ID;
NSString *senderLogin = [LocalStorageController shared].qbUser.login;
NSMutableDictionary *senderLoginDictionary = [[NSMutableDictionary alloc]init];
[senderLoginDictionary setObject:senderLogin forKey:@"senderName"];
[message setCustomParameters:senderLoginDictionary];
[self sendMessageWithText:messageText];
// [[ServicesManager instance].chatService sendMessage:message toDialog:self.dialog save:YES completion:nil];
// clean text field
[self.messageTextField setText:nil];
}
#pragma mark - Sending
- (void) sendMessageWithText:(NSString*)text {
// send a message
BOOL sent = [[ChatService shared] sendMessage:text toDialog:self.dialog];
if(!sent){
[[TWMessageBarManager sharedInstance] showMessageWithTitle:@"Error"
description:@"Please check your internet connection"
type:TWMessageBarMessageTypeInfo];
return;
}
// reload table
[self.tableView reloadData];
if([[ChatService shared] messagsForDialogId:self.dialog.ID].count > 0){
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[[[ChatService shared] messagsForDialogId:self.dialog.ID] count]-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
}
#pragma mark
#pragma mark UITableViewDelegate & UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[[ChatService shared] messagsForDialogId:self.dialog.ID] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
QBChatMessage *message = [[ChatService shared] messagsForDialogId:self.dialog.ID][indexPath.row];
NSLog(@"messages in chatService: %lu", [[ChatService shared] messagsForDialogId:self.dialog.ID].count);
ChatMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ChatMessageCellIdentifier];
[cell configureCellWithMessage:message];
// static NSString *CellIdentifier = @"MessageCell";
// MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// cell.message = message;
cell.userInteractionEnabled = NO;
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
QBChatMessage *chatMessage = [[[ChatService shared] messagsForDialogId:self.dialog.ID] objectAtIndex:indexPath.row];
CGFloat cellHeight = [ChatMessageTableViewCell heightForCellWithMessage:chatMessage];
return cellHeight;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark
#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
#pragma mark - UIGestureRecognizer
- (void) messageTextFieldDidTap:(UITapGestureRecognizer*) gesture {
[self.messageTextField becomeFirstResponder];
}
#pragma mark
#pragma mark Keyboard notifications
- (void)keyboardWillShow:(NSNotification *)note
{
CGRect keyboardBounds = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardBounds.size.height, 0.0);
[self.tableView setContentInset:contentInsets];
[self.tableView setScrollIndicatorInsets:contentInsets];
if([[ChatService shared] messagsForDialogId:self.dialog.ID].count > 0){
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[[[ChatService shared] messagsForDialogId:self.dialog.ID] count]-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
[UIView animateWithDuration:0.3 animations:^{
self.inputBackgroundView.transform = CGAffineTransformMakeTranslation(0, -keyboardBounds.size.height);
}];
self.isKeyboradShow = YES;
}
- (void)keyboardWillHide:(NSNotification *)note
{
self.isKeyboradShow = NO;
[self.tableView setContentInset:UIEdgeInsetsZero];
[self.tableView setScrollIndicatorInsets:UIEdgeInsetsZero];
if([[ChatService shared] messagsForDialogId:self.dialog.ID].count > 0){
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[[[ChatService shared] messagsForDialogId:self.dialog.ID] count]-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
[UIView animateWithDuration:0.3 animations:^{
self.inputBackgroundView.transform = CGAffineTransformIdentity;
}];
}
#pragma mark
#pragma mark ChatServiceDelegate
- (void)chatDidLogin
{
// sync messages history
//
[self syncMessages:NO];
}
- (BOOL)chatDidReceiveMessage:(QBChatMessage *)message
{
//NSString *dialogId = message.dialogID;
// Reload table
[self syncMessages:YES];
[self.tableView reloadData];
if([[ChatService shared] messagsForDialogId:self.dialog.ID].count > 0){
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[[[ChatService shared] messagsForDialogId:self.dialog.ID] count]-1 inSection:0]
atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
return YES;
}
-(void) chatRoomDidReceiveMessage:(QBChatMessage *)message fromDialogID:(NSString *)dialogID {
if (dialogID == self.dialog.ID) {
}
[self fetchMessages];
// [self getPreviousMessages];
[self.tableView reloadData];
if([[ChatService shared] messagsForDialogId:self.dialog.ID].count > 0){
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[[[ChatService shared] messagsForDialogId:self.dialog.ID] count]-1 inSection:0]
atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
}
- (void) hideKeyboard {
[self.messageTextField resignFirstResponder];
}
- (void) fetchMessages {
NSMutableDictionary *extendedRequest = [NSMutableDictionary new];
NSDate *now = [NSDate date];
extendedRequest[@"date_sent[lte]"]= @([now timeIntervalSince1970]);
extendedRequest[@"sort_desc"]= @"date_sent";
// extendedRequest[@"limit"] = @(50);
QBResponsePage *page = [QBResponsePage responsePageWithLimit:100 skip:0];
[QBRequest messagesWithDialogID:self.dialog.ID extendedRequest:extendedRequest forPage:page successBlock:^(QBResponse *response, NSArray *messages, QBResponsePage *page) {
if(messages.count > 0){
[[ChatService shared] addMessages:messages forDialogId:self.dialog.ID];
NSLog(@"messages in request: %lu", messages.count);
self.messageArray = [NSMutableArray arrayWithArray:messages];
}
[self.tableView reloadData];
NSInteger count = [[ChatService shared] messagsForDialogId:self.dialog.ID].count;
if(count > 0){
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:count-1 inSection:0]
atScrollPosition:UITableViewScrollPositionBottom animated:NO];
}
} errorBlock:^(QBResponse *response) {
}];
}
#pragma mark - Property
@end
正在正确调用chatRoomDidReceiveMessage
之类的代理,但它不会将新消息添加到UI或其他任何内容。日志显示&#34;消息插入1&#34; &#34;用于更新1&#34;的对话框,但它不会更新任何内容。