如之前所说,建议建立一个XMPPStream单例对象,然后再在这个单例对象中进行模块添加,当然使用其他你认为合适的方式进行下面的模块添加也是OK的
XEP-0136:XMPPMessageArchiving(消息)
1,导入头文件
//消息模块
#import "XMPPMessageArchiving.h"
#import "XMPPMessageArchivingCoreDataStorage.h"
2, 模块添加
//消息模块
_messageStorage = [XMPPMessageArchivingCoreDataStorage sharedInstance];
_message = [[XMPPMessageArchiving alloc] initWithMessageArchivingStorage:self.messageStorage];
[_message activate:_xmppStream];
3,消息模块使用:
如果需要使用模块,需要把模块相应的对象暴漏到头文件中方便我们之后调用
在本模块中需要暴漏的是XMPPRoster对象和XMPPRosterCoreDataStorage,前者用来设置代理以监听数据变化更新等,后者需要用来获取数据上下文,进行数据查询,具体如下:
- 3.1, 从数据库中取值(CoreData数据库文件在工程中是在XMPPFramework文件夹下的Resources文件夹里)
//1,获取上下文
NSManagedObjectContext *context = [IMStream sharedStream].messageStorage.mainThreadManagedObjectContext;
//2, 创建表的请求并设置过滤条件以及排序等
NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"XMPPMessageArchiving_Message_CoreDataObject"];
NSString *account = [[NSUserDefaults standardUserDefaults] objectForKey:@"account"];
NSString *jid = [NSString stringWithFormat:@"%@@192.168.0.2", account];
NSString *friendJid = @"ivanl002@192.168.0.2";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"streamBareJidStr = %@ AND bareJidStr = %@",jid,friendJid];
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:YES];
fetch.predicate = predicate;
fetch.sortDescriptors = @[sort];
self.fetchController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetch managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
//2,设置代理方便监听
self.fetchController.delegate = self;
//3,真正的执行请求得到数据
NSError *error;
[self.fetchController performFetch:&error];
if (error) {
NSLog(@"%@",error);
}
NSLog(@"-------------------------%@",self.fetchController.fetchedObjects);
- 3.2,解析查询的结果
XMPPMessageArchiving_Message_CoreDataObject *cellData = self.fetchController.fetchedObjects[indexPath.row];
- 3.3,在合适的位置进行了数据的查询之后就可以进行数据变化的监听了
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller{
NSLog(@"内容发生了变化");
[self.tableView reloadData];
NSUInteger rowcount = controller.fetchedObjects.count-1;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:rowcount inSection:0];
[self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
- 3.4, 发送消息,只需要包装一下用XMPPStream发送就可以了
NSLog(@"发送消息");
NSString *friendJidStr = @"ivanl002@192.168.0.2";
XMPPJID *friendJid = [XMPPJID jidWithString:friendJidStr];
XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:friendJid];
[message addBody:@"这是一条新的消息"];
NSLog(@"message---------%@", message);
[[IMStream sharedStream].xmppStream sendElement:message];
4,释放模块,当你不需要再使用这个模块的时候可以释放掉这个模块(在单例中貌似没有这个必要,可以在控制器死亡的时候进行释放,具体放在那里看具体情况)
//首先冻结模块
[_message deactivate];
//然后把对象设置为nil
_message = nil;
_messageStorage = nil;