Xmpp notes: user network connection and friend management, xmpp network connection

Source: Internet
Author: User

Xmpp notes: user network connection and friend management, xmpp network connection

In xmppUser connection moduleIncluding display of user online and offline information, user logon, and user registration;Friend ModuleIncluding adding friends, deleting friends, and displaying friends lists.

XmppStream is the class responsible for data transmission in xmpp. during development, different proxy methods are called for different transmission content. When XMPPFramework is used for development, you only need to enter the same code in different proxy methods.

Previous review:

Xmpp Organization notes: import and introduction to xmppFramework http://www.cnblogs.com/dsxniubility/p/4307057.html

Xmpp Organization notes: Quick environment configuration (with installation package) http://www.cnblogs.com/dsxniubility/p/4304570.html

If you did not see this article in Dong Boran's blog, click to view the original article.

I. The approximate connection process is as follows:

1. After running, you need to establish a persistent connection with the server. The system will report whether the connection is successful.

2. When the operation succeeds, you need to tell the user's password of the server to determine whether the server is authorized.

3. After successful authorization, the server is notified to be online.

4. Tell the server when it is about to leave. I need to disconnect the connection.

5. The server reports that you can disconnect, and then you can tell the server that you are offline.


II. First, you need to know some proxy methods for XMPPStreamDelegate and XMPPRosterDelegate.

If you did not see this article in Dong Boran's blog Park, click to view the original article.

Xmpp stream proxy method:

Call upon successful connection

-(Void) xmppStreamDidConnect :( XMPPStream *) sender

Called when disconnected

-(Void) xmppStreamDidDisconnect :( XMPPStream *) sender withError :( NSError *) error

Called upon successful authorization

-(Void) xmppStreamDidAuthenticate :( XMPPStream *) sender

Call when authorization fails

-(Void) xmppStream :( XMPPStream *) sender didNotAuthenticate :( DDXMLElement *) error

Called upon successful registration

-(Void) xmppStreamDidRegister :( XMPPStream *) sender

Call when registration fails

-(Void) xmppStream :( XMPPStream *) sender didNotRegister :( DDXMLElement *) error

XmppRoster roster proxy method

Called when a friend request is received

-(Void) xmppRoster :( XMPPRoster *) sender didReceivePresenceSubscriptionRequest :( XMPPPresence *) presence


3. User Logon:

The user needs to send his/her password to the server in the proxy method after the connection is successful. His/her password should be saved to the preference setting together with other information when clicking login, it can be easily obtained as needed. AuthenticateWithPassword will be used when sending the verification request: the following error is recommended to be handled in actual development. I am lazy here as follows:

/** Call upon successful connection */-(void) xmppStreamDidConnect :( XMPPStream *) sender {NSLog (@ "connection successful"); NSString * password = [[NSUserDefaults standardUserDefaults] valueForKey: SXLoginPasswordKey]; // send the user password to the server to log on to [self. xmppStream authenticateWithPassword: password error: NULL];}

Then, wait for the result. After the authorization is successful, the proxy method that comes to the successful authorization should first tell the server user to go online, and then send a success notification. Your AppDelegate will receive it in the distance, once a notification is received, the root controller of the application is changed immediately to the interface after the entry. Note that these proxy methods are asynchronous, so inter-thread communication is required, send notifications in the main thread

// Notify the server user to go online [self goOnline]; // broadcast dispatch_async (dispatch_get_main_queue (), ^ {[[nsicationicationcenter defacenter center] postNotificationName: SXLoginResultNotification object: @ (YES)] ;});

If authorization fails, the connection to the server should be closed and the user preferences of the initial storage should be cleared (because these are incorrect and useless ), then, go to the main thread to update the UI. A dialog box is displayed, showing the Password error and sending a failure notification. Let APPDelegate switch the root controller to the logon interface (originally edited by Dong baoran)

// Disconnect from the server [self disconnect]; // CLEAR user preferences [self clearUserDefaults]; // update the UI if (self. failed) {dispatch_async (dispatch_get_main_queue (), ^ {self. failed (@ "incorrect user name or password! ") ;}) ;}// Broadcast dispatch_async (dispatch_get_main_queue (), ^ {[[nsicationicationcenter defacenter center] postNotificationName: SXLoginResultNotification object in the main thread using notifications: @ (NO)] ;});


4. User online and offline:

An XMPPPresence class is required for online and offline users. This class is a subclass of XMPPElement and is mainly used to manage the display of certain information. First, you need to instantiate an object, which uses a presenceWithType method. There are two options: @ "unavailable" indicates deprecation, and @ "available" indicates launching, generally, it can be omitted directly after the launch. After instantiation, the xmpp stream is used for sending out. As shown below

# Pragma mark-********************** publish and deprecate a user-(void) goOnline {XMPPPresence * p = [XMPPPresence presence]; [self. xmppStream sendElement: p];}-(void) goOffline {XMPPPresence * p = [XMPPPresence presenceWithType: @ "unavailable"]; [self. xmppStream sendElement: p];}

Determine whether a user is online

// Retrieve the user XMPPUserCoreDataStorageObject * user = [self. fetchedResultsController objectAtIndexPath: indexPath];

User. section indicates the user's status.

// Section // 0 online // 1 left // 2 offline



5. User Registration:

Build your own registration page in the UI, which requires the user to fill in the user information. When you click the register button, set a Boolean isRegisterUser set in the singleton class to YES. Then resend the connection request. The proxy method used when the connection is successful. I sent a user password to log on here. Now I can add a layer of judgment, if the value of isRegisterUser is YES, it is not to send the User Password Logon, but to send the User Password registration. Here, a method registerWithPassword will be used:

If (self. isRegisterUser) {// send the user password to the server for user registration [self. xmppStream registerWithPassword: password error: NULL]; // reset the registration mark self. isRegisterUser = NO ;}

There are two proxy methods, registration is successful and registration fails, write the appropriate operation respectively.


Sat. Add friends:

To build a friend-adding UI, you only need a text box and a button.

In the text box, press the enter button and click the proxy method to check whether the text box is empty. If it is not empty, add a friend. (The add friend method can be extracted and written to make the structure clearer)

The method for adding a friend is as follows: one of the two notes is to determine whether a user has written a domain name. If only one account is written, the user can also automatically splice a domain name for him and then register it. Another way is to determine whether you are a friend of your own. If you are a friend, you will not perform any operations. If it is not a friend, add it immediately. Finally, let the navigation controller return to the login interface

// Add a friend-(void) addFriendWithName :( NSString *) name {// you write the domain name, which is better. If you do not write the system, it will automatically help you add the nsange range = [name rangeOfString: @ "@"]; // if NSNotFound is not found, do not write 0 if (range. location = NSNotFound) {name = [name stringByAppendingFormat: @ "@ % @", [SXXMPPTools sharedXMPPTools]. xmppStream. myJID. domain];} // if you are already a friend, you do not need to add XMPPJID * jid = [XMPPJID jidWithString: name]; BOOL contains = [[SXXMPPTools sharedXMPPTools] again. xmppRosterCoreDataStorage userExistsWithJID: jid xmppStream: [SXXMPPTools sharedXMPPTools]. xmppStream]; if (contains) {[[[UIAlertView alloc] initWithTitle: @ "prompt" message: @ "already a friend, no need to add" delegate: nil cancelButtonTitle: @ "OK" otherButtonTitles: nil, nil] show]; return;} [SXXMPPTools sharedXMPPTools]. xmppRoster subscribePresenceToUser: jid]; [self. navigationController popViewControllerAnimated: YES];}

Here we will use the subscribePresenceToUser method that adds friends through JID: But this method is called by Roster. Therefore, we need to import the header file declaration attribute in the singleton class to comply with the Protocol, proxy method implementation (originally implemented by Dong baoran)

In a singleton class, all the operations of special classes must be written in the lazy loading of xmppStream.

// Instantiate _ xmppReconnect = [[XMPPReconnect alloc] init]; _ region = [sharesharedinstance]; _ xmppRoster = [[XMPPRoster alloc] region: _ xmppRosterCoreDataStorage dispatchQueue: Queue (0, 0)]; // activate [_ xmppRoster activate: _ xmppStream]; // Add a proxy [_ xmppRoster addDelegate: self delegateQueue: dispatch_get_main_queue ()];


Proxy Method for receiving friend adding requests

-(Void) xmppRoster :( XMPPRoster *) sender didReceivePresenceSubscriptionRequest :( XMPPPresence *) presence

In this method, we first need to splice the prompt string, that is, to request you as a friend from the person in presence. from (Applicant's id. Then, set the pop-up window, click OK, and then click OK.

// Accept friend requests [self. xmppRoster acceptPresenceSubscriptionRequestFrom: presence. from andAddToRoster: YES];

We recommend that you use the new function UIAlertController of ios8. In this way, you do not need to write alertDelegate, but you can also set the OK button click event. Use the alert addAction: Add button, write the click event in the block, and finally get the root controller of the current window to bring up presentViewController, which is equivalent to the previous show. IOS 8 Apple's idea is gradually to gradually unify all the pop-up controller methods to the present.

Supplement: This function is called "Add friends" on QQ and does not need to be verified. It is a Boolean value that can be used to control the switch.

// Cancel the automatic subscription reception function. You need to confirm before you can add friends! _ XmppRoster. autoAcceptKnownPresenceSubscriptionRequests = NO;


7. Displays a friend list.

The query result scheduler is used here.

-(NSFetchedResultsController *) fetchedResultsController {if (_ fetchedResultsController! = Nil) {return _ fetchedResultsController;} // specify the queried object NSFetchRequest * request = [[NSFetchRequest alloc] initWithEntityName: @ "XMPPUserCoreDataStorageObject"]; // sort online status NSSortDescriptor * sort1 = [NSSortDescriptor sortDescriptorWithKey: @ "sectionNum" ascending: YES]; // sort the display names NSSortDescriptor * sort2 = [NSSortDescriptor listener: @ "displayName" ascending: YES]; // Add a sort request. sortDescript Ors = @ [sort1, sort2]; // Add predicateWithFormat = [NSPredicate predicateWithFormat :@"! (Sub‑contains 'None') "]; // Add the context NSManagedObjectContext * ctx = [SXXMPPTools sharedXMPPTools]. xmppRosterCoreDataStorage. future; // instantiate the result controller _ fetchedResultsController = [[externalloc] initWithFetchRequest: request managedObjectContext: ctx sectionNameKeyPath: nil cacheName: nil]; // set its proxy _ fetchedResultsController. delegate = self; return _ fetchedResultsController ;}

After writing the result scheduler, remember to add a sentence to the first load on the viewdidload page; otherwise, do not work.

// Query data [self. fetchedResultsController into mfetch: NULL];


The result scheduler has a proxy method that is triggered when the context changes, that is, a friend is added or a friend is deleted.

-(Void) controllerDidChangeContent :( NSFetchedResultsController *) controller {NSLog (@ "Context Change"); [self. tableView reloadData];}


The data source method for the entire tableview is as follows:

-(NSInteger) tableView :( UITableView *) tableView numberOfRowsInSection :( NSInteger) section {return self. fetchedResultsController. fetchedObjects. count;}-(UITableViewCell *) tableView :( UITableView *) tableView cellForRowAtIndexPath :( NSIndexPath *) indexPath {static NSString * ID = @ "ContactCell"; UITableViewCell * cell = [tableView labels: ID]; XMPPUserCoreDataStorageObject * user = [Self. fetchedResultsController objectAtIndexPath: indexPath]; // displays whether this friend is interested in NSString * str = [user. jidStr stringByAppendingFormat: @ "| % @", user. subtasks]; cell. textLabel. text = str; // here, a custom method is provided to pass in the section. The switch function is used to determine the returned Chinese characters. Section is related to whether cell. detailTextLabel. text = [self userStatusWithSection: user. section]; return cell ;}

Subscribe is the mutual addition of your friends.

// If it is none, it indicates that the other party has not confirmed it. // to me to follow the other party // from the other party to follow me // both mutual Powder

The user. section is the user's status.

// Section // 0 online // 1 left // 2 offline

When a friend goes online and the context changes, the result scheduler sorts the messages again and displays the online friends.


8. Delete friends

You can add sliding deletion to tableView on the list display page of a friend. (Enable edit mode)

# Pragma mark-********************* enable edit mode to delete a friend-(void) tableView :( UITableView *) tableView commitEditingStyle :( UITableViewCellEditingStyle) editingStyle forRowAtIndexPath :( NSIndexPath *) indexPath {if (editingStyle = UITableViewCellEditingStyleDelete) {XMPPUserCoreDataStorageObject * user =. fetchedResultsController objectAtIndexPath: indexPath]; XMPPJID * jid = user. jid; // set the pop-up window

In the pop-up window Click Event, the method used to delete a friend is

[[SXXMPPTools sharedXMPPTools].xmppRoster removeUser:jid];



If you did not see this article in Dong Boran's blog, click to view the original article.

I am sorting out various details about the information sending module. If you are interested, please pay attention to it.

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.