标签:imp set share dma priority art filter timestamp content
今天開始做到最基本的功能发送和接收消息、获取本地历史数据。
先上到眼下为止的效果图:
首先是要在XMPPFramework.h中引入数据存储模块:
//聊天记录模块的导入 #import "XMPPMessageArchiving.h" #import "XMPPMessageArchivingCoreDataStorage.h" #import "XMPPMessageArchiving_Contact_CoreDataObject.h" //近期联系人 #import "XMPPMessageArchiving_Message_CoreDataObject.h"
//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]; }
XMPP系列(四)---发送和接收文字消息,获取历史消息功能
标签:imp set share dma priority art filter timestamp content
原文地址:http://www.cnblogs.com/yutingliuyl/p/7045304.html