Saving XMPPMessage in CoreData in XMPPFrameWork ios

帅比萌擦擦* 提交于 2019-12-13 16:27:03

问题


I am working on a chat application and using xmppframework .Now there is a need for storing message in a persistent storage. Can anyone tell me how can i store and retrieve message from CoreData in IOS.


回答1:


Since you're using github/robbiehanson/XMPPFramework, it's easy to get both your incoming and outgoing message stored during initializing:

//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()];

To retrieve the saved message, here's the sample code in my project:

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"



回答2:


Are you using https://github.com/robbiehanson/XMPPFramework If yes then it by defaults implements core data and you just have to make minor changes to get the chat message...



来源:https://stackoverflow.com/questions/20609824/saving-xmppmessage-in-coredata-in-xmppframework-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!