在XMPPFrameWork ios中保存CoreData中的XMPPMessage

时间:2013-12-16 11:29:37

标签: ios save message xmppframework

我正在使用聊天应用程序并使用xmppframework。现在需要将消息存储在持久存储中。任何人都可以告诉我如何在IOS中存储和检索来自CoreData的消息。

2 个答案:

答案 0 :(得分:5)

由于您正在使用github / robbiehanson / XMPPFramework,因此在初始化期间可以轻松获取传入和传出消息:

//this code init your XMPPStream
xmppStream = [[XMPPStream alloc]init];
[xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
xmppStream.autoStartTLS = YES;

xmppReconnect = [[XMPPReconnect alloc]init];
[xmppReconnect activate:self.xmppStream];

xmppMessageArchivingCoreDataStorage = [XMPPMessageArchivingCoreDataStorage sharedInstance];
xmppMessageArchivingModule = [[XMPPMessageArchiving alloc]initWithMessageArchivingStorage:xmppMessageArchivingCoreDataStorage];
[xmppMessageArchivingModule setClientSideMessageArchivingOnly:YES];
[xmppMessageArchivingModule activate:xmppStream];    //By this line all your messages are stored in CoreData
[xmppMessageArchivingModule addDelegate:self delegateQueue:dispatch_get_main_queue()];

要检索已保存的消息,请参阅我的项目中的示例代码:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

NSManagedObjectContext *context = [self.xmppMessageArchivingCoreDataStorage mainThreadManagedObjectContext];
NSEntityDescription *messageEntity = [NSEntityDescription entityForName:@"XMPPMessageArchiving_Message_CoreDataObject" inManagedObjectContext:context];

fetchRequest.entity = messageEntity;

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:NO];
fetchRequest.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:fetchRequest error:&error];
//Now you get the NSArray with element type of "XMPPMessageArchiving_Message_CoreDataObject"

答案 1 :(得分:0)

您使用的是https://github.com/robbiehanson/XMPPFramework吗? 如果是,则默认情况下它会实现核心数据,您只需进行微小的更改即可获得聊天消息...