A brief introduction to IOS Xmppframework (realizing timely communication) _ios

Source: Internet
Author: User
Tags addchild xmlns

Xmppframework is an open source project for an OS X/ios platform that uses OBJECTIVE-C to implement the XMPP Protocol (RFC-3920) and also provides tools for reading and writing XML, greatly simplifying the development of XMPP based communications applications.

1. Login and friends on the offline

Common objects in 1.1XMPP

    • XMPPSTREAM:XMPP Basic Service class
    • Xmpproster: Buddy List class
    • Xmpprostercoredatastorage: Buddy list (user account) Action class in core data
    • Xmppvcardcoredatastorage: Friends Business Card (nickname, signature, gender, age, etc.) in core data operation class
    • Xmppvcardtemp: Friends Business Card entity class, from the database is taken out of it
    • Xmppvcardavatarmodule: Friend Avatar
    • Xmppreconnect: Automatically reconnect if the connection is lost
    • Xmpproom: Multi-user chat support available
    • Xmpppubsub: Publish Subscriptions

1.2 login operation, which is to connect XMPP server

-(void) Connect {
  if (Self.xmppstream = = nil) {
    self.xmppstream = [[Xmppstream alloc] init];
    [Self.xmppstream adddelegate:self Delegatequeue:dispatch_get_main_queue ()];
  }
  if (![ Self.xmppstream isconnected]) {
    NSString *username = [[Nsuserdefaults standarduserdefaults] objectForKey:@ ' Username "];
    Xmppjid *jid = [Xmppjid jidwithuser:username domain:@ "Lizhen" resource:@ "Ework"];
    [Self.xmppstream Setmyjid:jid];
    [Self.xmppstream sethostname:@ "10.4.125.113"];
    Nserror *error = nil;
    if (![ Self.xmppstream Connect:&error]) {
      NSLog (@ "Connect error:%@", [[[Error UserInfo] description]);
    }
}

Connect succeeds and then calls the Xmppstreamdelegate method, calling first

-(void) Xmppstream: (Xmppstream *) sender Socketdidconnect: (Gcdasyncsocket *) socket

And then

-(void) Xmppstreamdidconnect: (Xmppstream *) sender

Under this method need to use Xmppstream Authenticatewithpassword method for password verification, success will respond to the delegate method, is the following

-(void) Xmppstreamdidauthenticate: (Xmppstream *) sender

1.3 Online

Implementation-(void) Xmppstreamdidauthenticate: (Xmppstream *) Sender Delegate method

-(void) Xmppstreamdidauthenticate: (Xmppstream *) Sender {
  xmpppresence *presence = [xmpppresence presencewithtype: @ "available"];
  [Self.xmppstream sendelement:presence];
}

1.4 Exit and Disconnect

-(void) Disconnect {
  xmpppresence *presence = [xmpppresence presencewithtype:@ "unavailable"];
  [Self.xmppstream sendelement:presence];
   
  [Self.xmppstream disconnect];
}

1.5 Buddy Status

Get the Buddy status by implementing

-(void) Xmppstream: (Xmppstream *) sender Didreceivepresence: (xmpppresence *) Presence
 
...

method, when the content of the presence tag is received, the xmppframework frame recalls the method

The format of a presence tag is generally as follows:

Status of Presence:

    • Available online
    • Away leave
    • Do not Disturb busy
    • Unavailable offline
-(void) Xmppstream: (Xmppstream *) sender Didreceivepresence: (xmpppresence *) presence {nsstring
  *presencetype = [ Presence type];
  NSString *presencefromuser = [[presence from] user];
  if (![ Presencefromuser isequaltostring:[[sender Myjid] user]) {
    if ([Presencetype isequaltostring:@ "available"]) {
      //
    } else if ([Presencetype isequaltostring:@ "Unavailable"]) {
      //
    }
  }
}

2. Receive messages and send messages

2.1 Receiving Messages

When the content of the message label is received, the xmppframework frame recalls the method

According to the XMPP protocol, the contents of the message body are stored inside the tag

-(void) Xmppstream: (Xmppstream *) sender Didreceivemessage: (xmppmessage *) message {
  NSString *messagebody = [ Message elementforname:@ the "body"] stringvalue];
}

2.2 Sending messages
To send a message, we need to put the data in the label according to the XMPP protocol, for example:

-(void) SendMessage: (NSString *) message Touser: (NSString *) User {
  nsxmlelement *body = [Nsxmlelement Elementwithnam e:@ "Body"];
  [Body setstringvalue:message];
  Nsxmlelement *message = [nsxmlelement elementwithname:@ "message"];
  [Message addattributewithname:@ "type" stringvalue:@ "chat"];
  NSString *to = [NSString stringwithformat:@ "%@ @example. com", user];
  [Message addattributewithname:@ ' to ' stringvalue:to];
  [Message addchild:body];
  [Self.xmppstream sendelement:message];
}

3. Get friends information and delete friends

3.1 Friends List and friends business cards

[_xmpproster fetchroster];//get buddy list
//get to a buddy node
-(void) Xmpproster: (Xmpproster *) sender Didrecieverosteritem: (nsxmlelement *) Item
//Get finished buddy list
-(void) xmpprosterdidendpopulating: (Xmpproster *) Sender
//to the server request contact card information
-(void) Fetchvcardtempforjid: (Xmppjid *) Jid;
Request a contact card, if the database is not requested, do not send business Card request
-(void) Fetchvcardtempforjid: (Xmppjid *) Jid ignorestorage: (BOOL) Ignorestorage;
Get the contact's business card, if the database returns, does not return empty, and crawls to the server
-(xmppvcardtemp *) Vcardtempforjid: (Xmppjid *) Jid Shouldfetch: (BOOL) Shouldfetch;
Update your own business card information
-(void) Updatemyvcardtemp: (Xmppvcardtemp *) vcardtemp;
Get a callback for a box of contact's business card information
-(void) Xmppvcardtempmodule: (Xmppvcardtempmodule *) Vcardtempmodule 
    Didreceivevcardtemp: (xmppvcardtemp *) vcardtemp 
           Forjid: (Xmppjid *) Jid

3.2 Add Friends

 Name is User account
  -(void) Xmppaddfriendsubscribe: (NSString *) name
  {
    //xmpphost is the server name, host name
    Xmppjid *jid = [ Xmppjid jidwithstring:[nsstring stringwithformat:@ "%@@%@", Name,xmpphost];
    [Presence addattributewithname:@ "subscription" stringvalue:@ "friend"];
    [Xmpproster Subscribepresencetouser:jid];
     
  }

3.3 Receive a request to add a friend

 -(void) Xmpproster: (Xmpproster *) sender Didreceivepresencesubscriptionrequest: (xmpppresence *) presence
  {
    / /Get Buddy status
    nsstring *presencetype = [NSString stringwithformat:@ "%@", [Presence type]];//online/offline
    //requested user
    nsstring *presencefromuser =[nsstring stringwithformat:@ "%@", [[Presence from] user]];
    NSLog (@ "presencetype:%@", presencetype);
     
    NSLog (@ "presence2:%@ sender2:%@", presence,sender);
     
    Xmppjid *jid = [Xmppjid jidwithstring:presencefromuser];
    Receive add buddy request
    [Xmpproster Acceptpresencesubscriptionrequestfrom:jid andaddtoroster:yes];
     
  }

3.4 Delete Friends

Delete buddy, name is Friend account
-(void) Removebuddy: (NSString *) name 
{ 
  Xmppjid *jid = [Xmppjid jidwithstring:[ NSString stringwithformat:@ "%@@%@", Name,xmpphost]; 
    
  [Self xmpproster] removeuser:jid]; 

4. Chat Room

Initialize chat room

Xmppjid *roomjid = [Xmppjid Jidwithstring:room_jid];
   
  Xmpproom = [[Xmpproom alloc] initwithroomstorage:self Jid:roomjid];
   
  [Xmpproom Activate:xmppstream];
  [Xmpproom adddelegate:self Delegatequeue:dispatch_get_main_queue ()];

Create chat Room Success

-(void) Xmpproomdidcreate: (Xmpproom *) sender
  {
    ddloginfo (@ "%@:%@", This_file, This_method);
  }

Join chat room, use nickname

 [Xmpproom joinroomusingnickname:@ "quack" history:nil];

Get chat Room Information

  -(void) Xmpproomdidjoin: (Xmpproom *) sender
  {
    [xmpproom fetchconfigurationform];
    [Xmpproom fetchbanlist];
    [Xmpproom fetchmemberslist];
    [Xmpproom fetchmoderatorslist];
  }

If the room exists, the delegate is invoked

 Receive a list of prohibited lists
  -(void) Xmpproom: (Xmpproom *) sender Didfetchbanlist: (Nsarray *) items;
  Receive list of Friends
  -(void) Xmpproom: (Xmpproom *) sender Didfetchmemberslist: (Nsarray *) items;
  Received list of hosts
  -(void) Xmpproom: (Xmpproom *) sender Didfetchmoderatorslist: (Nsarray *) items;

Room does not exist, call delegate

 -(void) Xmpproom: (Xmpproom *) sender Didnotfetchbanlist: (XMPPIQ *) Iqerror;
  -(void) Xmpproom: (Xmpproom *) sender Didnotfetchmemberslist: (XMPPIQ *) Iqerror;
  -(void) Xmpproom: (Xmpproom *) sender Didnotfetchmoderatorslist: (XMPPIQ *) Iqerror;

Leave the room

[Xmpproom Deactivate:xmppstream];

Other proxy methods for Xmpproomdelegate:

Leave the chat room

 -(void) Xmpproomdidleave: (Xmpproom *) sender
  {
    ddlogverbose (@ "%@:%@", This_file, This_method);
  }

New people join Group chat

 -(void) Xmpproom: (Xmpproom *) sender Occupantdidjoin: (Xmppjid *) Occupantjid
  {
    ddlogverbose (@ "%@:%@", This_ FILE, This_method);
  }

Someone quit the group chat

 -(void) Xmpproom: (Xmpproom *) sender Occupantdidleave: (Xmppjid *) Occupantjid
  {
    ddlogverbose (@ "%@:%@", this _file, This_method);
  

Someone is speaking in the group.

 -(void) Xmpproom: (Xmpproom *) sender Didreceivemessage: (xmppmessage *) message fromoccupant: (Xmppjid *) Occupantjid
  {
    ddlogverbose (@ "%@:%@", This_file, This_method);
  }

5. Message Receipt

This is the content of the XEP-0184 agreement. Protocol content:

Attach a receipt request when sending a message

Code implementation

NSString *siid = [Xmppstream generateuuid];
  Send Message
  xmppmessage *message = [xmppmessage messagewithtype:@ "chat" To:jid elementid:siid];
  Nsxmlelement *receipt = [nsxmlelement elementwithname:@ "Request" xmlns:@ "urn:xmpp:receipts"];
  [Message addchild:receipt];
  [Message addbody:@ "test"];
  [Self.xmppstream Sendelement:message];

Receive a receipt request message, send a receipt

Code implementation

 -(void) Xmppstream: (Xmppstream *) sender Didreceivemessage: (xmppmessage *) message {//receipt judgment Nsxmlelement *reques
    t = [message elementforname:@ "request"];
        if (request) {if ([Request.xmlns isequaltostring:@ "urn:xmpp:receipts"])//Message Receipts {//Assembly message Receipts Xmppmessage *msg = [xmppmessage messagewithtype:[message attributestringvalueforname:@ ' type '] To:message.from
        Elementid:[message attributestringvalueforname:@ "id"]];
        Nsxmlelement *recieved = [Nsxmlelement elementwithname:@ "received" xmlns:@ "urn:xmpp:receipts"];
         
        [MSG addchild:recieved];
      Send receipts [Self.xmppstream sendelement:msg];
      }}else {Nsxmlelement *received = [Message elementforname:@ ' received '];
          if (Received) {if ([Received.xmlns isequaltostring:@ "urn:xmpp:receipts"])//message Receipt {//Sent successfully 
     
    NSLog (@ "message send success!");}}
 Message Handling//...}

6. Add autoping

To monitor whether the server is valid, increase heartbeat monitoring. With the XEP-0199 protocol, it is possible to encapsulate the xmppautoping and xmppping two classes under the Xmppframework framework, because xmppautoping has been combined into the Xmppping class, So xmppautoping is more convenient to use.

Initialize and start ping-(void) Autopingproxyserver: (nsstring*) strproxyserver {_xmppautoping = [[Xmppautopingalloc] init];
  [_xmppautopingactivate:_xmppstream];
  [_xmppautopingadddelegate:selfdelegatequeue:dispatch_get_main_queue ()];
  _xmppautoping.respondstoqueries = YES; _xmppautoping.pinginterval=2;//ping interval if (nil!= strproxyserver) {_xmppautoping.targetjid = [Xmppjid jidWithSt
 Ring:strproxyserver];//Set Ping the target server and, if it is nil, listen for the server on the current connection Socketstream}//uninstall listening [_xmppautoping deactivate];
  [_xmppautoping removedelegate:self];
_xmppautoping = nil; Ping Xmppautopingdelegate Delegate method:-(void) xmppautopingdidsendping: (xmppautoping *) Sender {NSLog (@ "-(void)
Xmppautopingdidsendping: (xmppautoping *) sender "); }-(void) Xmppautopingdidreceivepong: (xmppautoping *) Sender {NSLog (@)-(void) Xmppautopingdidreceivepong: (
xmppautoping *) sender "); }-(void) Xmppautopingdidtimeout: (xmppautoping *) Sender {NSLog (@)-(void) Xmppautopingdidtimeout: (xmppautoping *) send
Er ");
 }

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.