今天开始做到最主要的功能发送和接收消息、获取本地历史数据。
先上到目前为止的效果图:
首先是要在XMPPFramework.h中引入数据存储模块:
//聊天记录模块的导入
#import "XMPPMessageArchiving.h"
#import "XMPPMessageArchivingCoreDataStorage.h"
#import "XMPPMessageArchiving_Contact_CoreDataObject.h" //最近联系人
#import "XMPPMessageArchiving_Message_CoreDataObject.h"
然后在XMPPStream中添加数据存储模块,因为XMPP框架默认用CoreData存储数据,而且做好了数据存储,因此我们只需要在合适的地方发送通知处理信息即可。
//4.消息模块,这里用单例,不能切换账号登录,否则会出现数据问题。
_xmppMessageArchivingCoreDataStorage = [XMPPMessageArchivingCoreDataStorage sharedInstance];
_xmppMessageArchiving = [[XMPPMessageArchiving alloc] initWithMessageArchivingStorage:_xmppMessageArchivingCoreDataStorage dispatchQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 9)];
[_xmppMessageArchiving activate:self.xmppStream];
在数据存储完毕后,发送通知:
在XMPPMessageArchivingCoreDataStorage的
- (void)archiveMessage:(XMPPMessage *)message outgoing:(BOOL)isOutgoing xmppStream:(XMPPStream
*)xmppStream结尾处添加如下通知:
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:kXMPP_MESSAGE_CHANGE object:nil];
});
现在去聊天界面获取历史消息吧:
/** 查询聊天记录 */
- (void)getChatHistory
{
XMPPMessageArchivingCoreDataStorage *storage = [JKXMPPTool sharedInstance].xmppMessageArchivingCoreDataStorage;
//查询的时候要给上下文
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:storage.messageEntityName inManagedObjectContext:storage.mainThreadManagedObjectContext];
[fetchRequest setEntity:entity];
// Specify criteria for filtering which objects to fetch
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"bareJidStr = %@", self.chatJID.bare];
[fetchRequest setPredicate:predicate];
// Specify how the fetched objects should be sorted
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timestamp"
ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]]; NSError *error = nil;
NSArray *fetchedObjects = [storage.mainThreadManagedObjectContext executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects != nil) {
self.chatHistory = [[NSMutableArray alloc] initWithArray:fetchedObjects];
// [NSMutableArray arrayWithArray:fetchedObjects];
} [self.messageTableView reloadData]; [self tableViewScrollToBottom];
}
消息接收也调用getChatHistory方法即可
而消息的发送是:
/** 发送的事件 */
- (void)sendMessage{
if (_chatTextField.text.length < 1) {
return;
}
XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:self.chatJID];
[message addBody:_chatTextField.text];
[[JKXMPPTool sharedInstance].xmppStream sendElement:message]; _chatTextField.text = @""; [self tableViewScrollToBottom];
}