Wednesday, February 17, 2016

Objecive C getting old messages or chat history from XMPP



In any chat application, we need to store the offline messages in case the user is in offline mode. And after user is online, We need to push all those chat messages to user. Otherwise, users will miss all the messages they got when they were offline. If we don't give this offline storage option, they may loose some important messages and they will not show interest on our app.

Openfire server is having an option to store offline messages.

We need to install Monitoring service plugin to enable message archiving. You may have to upgrade your openfire service if this plugin is not appearing in your available plugins section in the admin console.



We will need to log into the admin console and go to the below setting

Server --> Archiving --> Archiving Settings 

to enable message archiving.

Here is the Objective C code to fetch chat history.



 NSXMLElement
 *iQ = [NSXMLElement elementWithName:@"iq"];

[iQ addAttributeWithName:@"type" stringValue:@"get"];
[iQ addAttributeWithName:@"id" stringValue:@"987654321"];

NSXMLElement *list = [NSXMLElement elementWithName:@"list"];

[list addAttributeWithName:@"xmlns" stringValue:@"urn:xmpp:archive"];
[list addAttributeWithName:@"with" stringValue:@"karun@mydomain.com"];

NSXMLElement *set = [NSXMLElement elementWithName:@"set"];

[set addAttributeWithName:@"xmlns" 
            stringValue:@"http://jabber.org/protocol/rsm"];


NSXMLElement *max = [NSXMLElement elementWithName:@"max"];

[max addAttributeWithName:@"xmlns" 
             stringValue:@"http://jabber.org/protocol/rsm"];

max.stringValue = @"30";

[set addChild:max];

[list addChild:set];
[iQ addChild:list];


[[[self appDelegate] xmppStream] sendElement:iQ];



Hope this post is useful. Feel free to comment in case of any queries.