Wednesday, February 17, 2016

Objective C XMPP searching users by username

In my XMPP User Registration post, We discussed about user registration to Openfire server using XMPP framework. After registration, as Openfire server is used for chatting, We need to provide a search option to the users, So that they will check for their friends and get connected to them and start chatting with them.



In this post, Let's discuss on how to search for users who are already registered in our XMPP server based on the below search parameters.



  • Username
  • Full name
  • Email


Here is the piece of code for this in Objective C. 



NSString *userBare  = [[[[self appDelegate] xmppStream] myJID] bare];    

NSXMLElement *query = [NSXMLElement elementWithName:@"query"];
[query addAttributeWithName:@"xmlns" stringValue:@"jabber:iq:search"];


NSXMLElement *x = [NSXMLElement elementWithName:@"x" xmlns:@"jabber:x:data"];
[x addAttributeWithName:@"type" stringValue:@"submit"];

NSXMLElement *formType = [NSXMLElement elementWithName:@"field"];
[formType addAttributeWithName:@"type" stringValue:@"hidden"];
[formType addAttributeWithName:@"var" stringValue:@"FORM_TYPE"];
[formType addChild:[NSXMLElement elementWithName:@"value" stringValue:@"jabber:iq:search" ]];

NSXMLElement *userName = [NSXMLElement elementWithName:@"field"];
[userName addAttributeWithName:@"var" stringValue:@"Username"];
[userName addChild:[NSXMLElement elementWithName:@"value" stringValue:@"1" ]];

NSXMLElement *name = [NSXMLElement elementWithName:@"field"];
[name addAttributeWithName:@"var" stringValue:@"Name"];
[name addChild:[NSXMLElement elementWithName:@"value" stringValue:@"1"]];

NSXMLElement *email = [NSXMLElement elementWithName:@"field"];
[email addAttributeWithName:@"var" stringValue:@"Email"];
[email addChild:[NSXMLElement elementWithName:@"value" stringValue:@"1"]];

NSXMLElement *search = [NSXMLElement elementWithName:@"field"];
[search addAttributeWithName:@"var" stringValue:@"search"];
[search addChild:[NSXMLElement elementWithName:@"value" stringValue:searchField]];

[x addChild:formType];
[x addChild:userName];
[x addChild:name];
[x addChild:email];
[x addChild:search];

[query addChild:x];


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