[IPhone advanced] XMPP-based IOS chat client (IOS client 2)

Source: Internet
Author: User

Next, we will introduce XMPP in this chapter.

To facilitate program calling, we will write some main XMPP methods in appdelegate.


The methods in appdelegate. m are as follows:

-(Void) setupstream {// initialize xmppstream = [[xmppstream alloc] init]; [xmppstream adddelegate: Self delegatequeue: Upload ()];}-(void) goonline {// sending online status xmpppresence * presence = [xmpppresence presence]; [[self xmppstream] sendelement: Presence];}-(void) gooffline {// sending offline status xmpppresence * presence = [xmpppresence presencewithtype: @ "unavailable"]; [[self xmppstream] sendelement: Presence];}-(bool) connect {[self setupstream]; // obtain the username, password, and server address from the local machine nsuserdefaults * defaults = [nsuserdefaults standarduserdefaults]; nsstring * userid = [defaults stringforkey: userid]; nsstring * pass = [defaults stringforkey: Pass]; nsstring * Server = [defaults stringforkey: Server]; If (! [Xmppstream isdisconnected]) {return yes;} If (userid = nil | pass = nil) {return no;} // set the user [xmppstream setmyjid: [xmppjid jidwithstring: userid]; // set the server [xmppstream sethostname: Server]; // Password = pass; // connect to the server nserror * error = nil; If (! [Xmppstream CONNECT: & error]) {nslog (@ "Cant connect % @", server); return no ;}return Yes ;}- (void) disconnect {[self gooffline]; [xmppstream Disconnect];}

These are the basic methods. The next step is the xmppstreamdelegate method, which is also an important method to accept the status of friends and messages.

// Connect to the server-(void) xmppstreamdidconnect :( xmppstream *) sender {isopen = yes; nserror * error = nil; // verify the password [[self xmppstream] authenticatewithpassword: Password error: & error];} // pass the verification-(void) xmppstreamdidauthenticate :( xmppstream *) sender {[self goonline];} // receive the message-(void) xmppstream :( xmppstream *) sender didreceivemessage :( xmppmessage *) Message {// nslog (@ "message = % @", message); nsstring * MSG = [[Message el Ementforname: @ "body"] stringvalue]; nsstring * From = [[Message attributeforname: @ "from"] stringvalue]; nsmutabledictionary * dict = [nsmutabledictionary]; [dict setobject: MSG forkey: @ "MSG"]; [dict setobject: From forkey: @ "sender"]; // message delegate (later) [messagedelegate newmessagereceived: dict];} // receive the friend status-(void) xmppstream :( xmppstream *) sender didreceivepresence :( xmpppresence *) Presence {// nslog (@ "Presence = % @", presence); // obtain the friend status nsstring * presencetype = [presence type]; // online/offline // The current user nsstring * userid = [[Sender myjid] user]; // The online user nsstring * presencefromuser = [[presence from] user]; If (! [Presencefromuser isinclutostring: userid]) {// online status if ([presencetype isinclutostring: @ "available"]) {// user list delegate (later) [chatdelegate newbuddyonline: [nsstring stringwithformat: @ "% @", presencefromuser, @ "nqc1338a"];} else if ([presencetype is#tostring: @ "unavailable"]) {// user list delegate (later) [chatdelegate buddywentoffline: [nsstring stringwithformat: @ "% @", presencefromuser, @ "nqc1338a"];}

There are two delegate methods, one is the user list delegate, and the other is the message delegate, the user list delegate is mainly to get online users, update the user tableview, A message delegate is to retrieve messages sent by a friend and update the tableview. Of course, the two tableviews are in different controllers.



After defining two delegates, we need to implement these two delegates in different controllers.

Implement <kkchatdelegate> In friend controller and write the following method:

// Obtain the delegate of the current program-(kkappdelegate *) appdelegate {return (kkappdelegate *) [[uiapplication sharedapplication] Delegate];} // obtain the current xmppstream-(xmppstream *) xmppstream {return [[self appdelegate] xmppstream];} // online friend-(void) newbuddyonline :( nsstring *) buddyname {If (! [Onlineusers containsobject: buddyname]) {[onlineusers addobject: buddyname]; [self. tview reloaddata] ;}}// void (void) buddywentoffline :( nsstring *) buddyname {[onlineusers removeobject: buddyname]; [self. tview reloaddata];}

Add in viewdidload

// Set the online user to delegate kkappdelegate * del = [self appdelegate]; del. chatdelegate = self;

These two lines of code enable the delegate implementation method of the friend list in this program

Add in viewwillappear

[Super viewwillappear: animated]; nsstring * login = [[nsuserdefaults standarduserdefaults] objectforkey: @ "userid"]; If (LOGIN) {If ([self appdelegate] connect]) {nslog (@ "show Buddy List") ;}} else {// set user [self account: Self];}

Determine whether userid exists in the locally stored data. If no, the logon page is displayed.

The most important thing here is connect. If you log on successfully, the page will display the friends list.

#pragma mark UITableViewDelegate-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{        //start a Chat    chatUserName = (NSString *)[onlineUsers objectAtIndex:indexPath.row];        [self performSegueWithIdentifier:@"chat" sender:self];    }-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{        if ([segue.identifier isEqualToString:@"chat"]) {        KKChatController *chatController = segue.destinationViewController;        chatController.chatWithUser = chatUserName;    }}


When a friend list is displayed, we select a friend to chat.

Send the current friend name to the chat page

Below is the chat Controller

Add in kkchatcontroller. h

NSMutableArray *messages;

This is the message we want to display. Each message is a dictionary.

Next, the message is displayed.

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{        static NSString *identifier = @"msgCell";        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];        if (cell == nil) {        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];    }        NSMutableDictionary *dict = [messages objectAtIndex:indexPath.row];        cell.textLabel.text = [dict objectForKey:@"msg"];    cell.detailTextLabel.text = [dict objectForKey:@"sender"];    cell.accessoryType = UITableViewCellAccessoryNone;        return cell;    }

Like the friend controller above, xmppstream is also required here.

-(KKAppDelegate *)appDelegate{        return (KKAppDelegate *)[[UIApplication sharedApplication] delegate];}-(XMPPStream *)xmppStream{        return [[self appDelegate] xmppStream];}

Add in viewdidload

KKAppDelegate *del = [self appDelegate];del.messageDelegate = self;

Set the message delegate to be received and processed by yourself

#pragma mark KKMessageDelegate-(void)newMessageReceived:(NSDictionary *)messageCotent{        [messages addObject:messageCotent];        [self.tView reloadData];    }

Next, the most important thing is to send messages.

-(Ibaction) sendbutton :( ID) sender {// The information in the local input box nsstring * message = self. messagetextfield. text; If (message. length> 0) {// xmppframework uses kissxml to generate an XML file // generate <body> document nsxmlelement * Body = [nsxmlelement elementwithname: @ "body"]; [Body setstringvalue: Message]; // generate the XML message document nsxmlelement * MEs = [nsxmlelement elementwithname: @ "message"]; // Message Type [mes addattributewithname: @ "type" stringvalue: @ "chat"]; // to [mes addattributewithname: @ "to" stringvalue: chatwithuser]; // who sends [mes addattributewithname: @ "from" stringvalue: [[nsuserdefaults standarduserdefaults] stringforkey: userid]; // combine [mes addchild: body]; // send a message [[self xmppstream] sendelement: MES]; self. messagetextfield. TEXT = @ ""; [self. messagetextfield resignfirstresponder]; nsmutabledictionary * dictionary = [nsmutabledictionary dictionary]; [dictionary setobject: Message forkey: @ "MSG"]; [dictionary setobject: @ "you" forkey: @ "sender"]; [messages addobject: dictionary]; // refresh tableview [self. tview reloaddata] ;}}

The above comments are added, so you should be aware that there is another chapter that will beautify the sent messages on the interface, just like the messages that come with Apple. Thank you for your patience. I don't like typing, so there are few comments in some places. I hope you don't mind. I also hope you can provide more support, in the future, we will introduce content such as XMPP file transmission.

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.