XMPP Finishing Notes: User network connections and management of friends

Source: Internet
Author: User

The user connection module in XMPP includes the user's online and offline information display, the user login, the user's registration, the friend module includes the friend's addition, the friend's deletion, the Friend list display.

In the XMPP is responsible for data transmission class is xmppstream, the development process, for different transmission content, will call different proxy methods, in the use of xmppframework development, only in different proxy methods, the same code can be filled in.

Past Period Review:

XMPP Grooming Notes: Xmppframework framework Import and introduction http://www.cnblogs.com/dsxniubility/p/4307057.html

XMPP Grooming Notes: Quick configuration of the environment (with installation package) http://www.cnblogs.com/dsxniubility/p/4304570.html

If you do not see this article in the Dong Platinum Blog Park, please click to view the original

One. The approximate connection process is as follows

1. After running, you need to establish a long connection with the server, the system will feedback whether the link is successful

2. Success needs to tell the server user's password, the server to determine whether to grant authorization

3. After successful authorization, tell the server to go online.

4. Tell the server when you're leaving, I need to disconnect the link.

5. Server feedback You can disconnect, and then you tell the server that you're offline.

Two. First, you need to know some proxy methods for Xmppstreamdelegate and Xmpprosterdelegate

If you are not in the Dong Platinum Blog Park See this article please click to view the original

XMPP Stream Proxy Method:

Called when the connection succeeds

-(void)Xmppstreamdidconnect:(Xmppstream *) sender

Called when a connection is disconnected

-(void)Xmppstreamdiddisconnect:(Xmppstream *) sender Witherror: (Nserror *) error

Called when authorization succeeds

-(void)xmppstreamdidauthenticate:(Xmppstream *) sender

Called when authorization fails

-(void) Xmppstream: (Xmppstream *) sender didnotauthenticate:(ddxmlelement *) error

Called when registration succeeds

-(void)Xmppstreamdidregister:(Xmppstream *) sender

Called when registration fails

-(void) Xmppstream: (Xmppstream *) sender Didnotregister:(ddxmlelement *) error

Xmpproster Roster Agent Method

Called when a friend request is received

-(void) Xmpproster: (Xmpproster *) sender didreceivepresencesubscriptionrequest:(xmpppresence *) presence

Three. User's login:

The user needs to send their own password to the server after the successful connection, and their password should be stored in the preferences with other information when the login is clicked, and it can be easily taken out when needed. This method is used when sending authentication requests Authenticatewithpassword: The following error is recommended in the actual development, I am lazy here as shown below

/** call */-(void) Xmppstreamdidconnect When the connection is successful: (Xmppstream *) sender{        NSLog (@ "Connection succeeded");            NSString *password = [[Nsuserdefaults standarduserdefaults] valueforkey:sxloginpasswordkey];        Send the user password to the server for user login        [self.xmppstream authenticatewithpassword:password error:null];}

And then wait for the result, after the authorization succeeds arrives the authorization succeeds the proxy method in this should first tell the server user to go online, then gives the successful notification, own appdelegate receives in the distant, once receives the notification immediately to replace the application's root controller to enters after the interface, here must Note that these proxy methods are asynchronous , so there is a need to use inter-thread communication and send notifications on the main threads

    Notifies the server user to go online    [self goonline];    The main thread uses notifications to send broadcast    Dispatch_async (Dispatch_get_main_queue (), ^{        [[Nsnotificationcenter Defaultcenter] Postnotificationname:sxloginresultnotification object:@ (YES)];    });

If the authorization fails, the link to the server should be disconnected, and the user preferences to start storing are emptied (because these are incorrect), and then a popup box to the main thread update UI displays the password error, and a failure notification is issued. Let appdelegate switch the root controller to the login interface (Dong Platinum original)

Disconnecting from the server    [self disconnect];    Clear user Preferences    [self clearuserdefaults];    In the main thread update UI    if (self.failed) {        Dispatch_async (dispatch_get_main_queue (), ^ {self.failed (@) Username or password error! ");});    }    The main thread uses notifications to send broadcast    Dispatch_async (Dispatch_get_main_queue (), ^{        [[Nsnotificationcenter Defaultcenter] Postnotificationname:sxloginresultnotification object:@ (NO)];    });

Four. User's online and offline:

On the user's on-line and offline, need to use a class Xmpppresence class. This class is a subclass of xmppelement that is used primarily to manage the presentation of certain information. First of all to instantiate an object, which will use a Presencewithtype method, There are two choices @ "unavailable" for the downline, @ "available" on behalf of the line, the general situation on the back of the line can be directly omitted. The instantiation is then sent out with the XMPP stream. As shown below

#pragma mark-******************** user's on-line and offline-(void) goonline {    xmpppresence *p = [xmpppresence presence];        [Self.xmppstream sendelement:p];} -(void) gooffline {    xmpppresence *p = [xmpppresence presencewithtype:@ "unavailable"];        [Self.xmppstream sendelement:p];}

Judgment on whether the user is online

Remove user Xmppusercoredatastorageobject *user = [Self.fetchedresultscontroller Objectatindexpath:indexpath];

The user's user.section is the user's state

Section//0 online//1 leave//2 offline

Five. User registration:

In the UI to build a good registration page, which requires users to fill in the user information. When you click the Register button, set the Boolean value isregisteruser you set in the Singleton class to Yes. Then resend the connection request. Eventually will come, the connection is successful when the proxy method, just here to send the user password login, now can add a layer of judgment, if the value of Isregisteruser is not to send the user password login, but to send the user password registration , A method Registerwithpassword will be used here:

if (self.isregisteruser) {        //Send user password to server for user registration        [self.xmppstream Registerwithpassword:password Error:null] ;        Resets the registration token to        self.isregisteruser = NO;    }

Then there are two proxy methods, registration success and registration failure, respectively, write the appropriate operation.

Six. Add Friends:

Building a friend's UI requires only a text box and a button.

In the text box of the return button click on the proxy method, do the text box is empty to judge, not empty to add friends, (Add a friend method can be extracted to write to make the structure clearer)

Add a friend method as follows: There are two points to note that one is to determine whether the user has written a domain name , if you just write an account, you can automatically help him to join the domain name and then register. Another is to determine whether you are already a friend, if you do not do anything. If it's not a friend, add it right away. Finally let the navigation controller return to the landing screen

//add Friend-(void) Addfriendwithname: (NSString *) name {//You write a domain name that's better, you don't write the system will automatically help you fill up    Nsrange range = [name rangeofstring:@ "@"]; If you do not find Nsnotfound, do not write 0 if (range.location = = nsnotfound) {name = [name stringbyappendingformat:@ "@%@", [SXXMP    Ptools 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].xmpprostercoredatastorage Userexistswithjid:jid xmppstream:[        Sxxmpptools Sharedxmpptools].xmppstream]; if (contains) {[[[Uialertview alloc] initwithtitle:@ "Prompt" message:@ "is 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 is a way to use a friend through Jid Subscribepresencetouser: But this method is called through the roster , so in a singleton class to import the header file declaration properties, abide by the Protocol, the implementation of proxy method (Dong Platinum original)

All special class operations in a singleton class are written in Xmppstream lazy loading.

        Instantiate        _xmppreconnect = [[Xmppreconnect alloc]init];        _xmpprostercoredatastorage = [Xmpprostercoredatastorage sharedinstance];        _xmpproster = [[Xmpproster alloc]initwithrosterstorage:_xmpprostercoredatastorage dispatchQueue:dispatch_get_ Global_queue (0, 0)];                Activate        [_xmpproster Activate:_xmppstream];        Add Agent        [_xmpproster adddelegate:self delegatequeue:dispatch_get_main_queue ()];                

Accept the proxy method to add Friend request

-(void) Xmpproster: (Xmpproster *) sender Didreceivepresencesubscriptionrequest: (xmpppresence *) presence

In this method, the first to stitching the hint of the string, that is, from the Presence.from (applicant's ID) of the person request to add you as a friend. Then set the pop-up window, OK and reject, click OK button after

Accept Friend Request        [Self.xmpproster AcceptPresenceSubscriptionRequestFrom:presence.from Andaddtoroster:yes];

This pop-up window suggests the use of IOS8 's new feature Uialertcontroller. This allows you to set the OK button click event without writing alertdelegate. With alert addaction: Add a button, write the Click event in block, and then take the root controller of the current window to bounce out the Presentviewcontroller, equivalent to the previous show. the idea of iOS8 Apple is gradually trying to unify all the methods of the pop-up controller to present.

Add: This function is QQ on the so-called plus friends do not need to verify, is a Boolean can control the switch.

        Cancel receiving automatic subscription function, need to confirm to be able to add friends!        _xmpproster.autoacceptknownpresencesubscriptionrequests = NO;

Seven. The display of your buddy list.

We need to use the query result scheduler.

-(Nsfetchedresultscontroller *) fetchedresultscontroller{if (_fetchedresultscontroller! = nil) {return _fetch    Edresultscontroller;        }//Specifies the entity of the query nsfetchrequest *request = [[Nsfetchrequest alloc]initwithentityname:@ "Xmppusercoredatastorageobject"];    Online status sequencing nssortdescriptor *sort1 = [Nssortdescriptor sortdescriptorwithkey:@ "Sectionnum" ascending:yes];        Display the name sort nssortdescriptor *sort2 = [Nssortdescriptor sortdescriptorwithkey:@ "DisplayName" ascending:yes];        Add sort request.sortdescriptors = @[sort1,sort2]; Add a predicate filter request.predicate = [Nspredicate predicatewithformat:@ "!        Subscription CONTAINS ' none ') "]; Add context Nsmanagedobjectcontext *ctx = [Sxxmpptools sharedxmpptools].        Xmpprostercoredatastorage.mainthreadmanagedobjectcontext; Instantiate result Controller _fetchedresultscontroller = [[Nsfetchedresultscontroller alloc]initwithfetchrequest:request        Managedobjectcontext:ctx Sectionnamekeypath:nil Cachename:nil]; Set up his agent.    _fetchedresultscontroller.delegate = self; return _fetchedresultscontroller;}

After writing the results of the scheduler to remember in the Viewdidload page first load add a sentence, or do not work

Querying data    [Self.fetchedresultscontroller performfetch:null];

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

-(void) Controllerdidchangecontent: (Nsfetchedresultscontroller *) controller{    NSLog (@ "context change");    [Self.tableview Reloaddata];}

The entire TableView data source method 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 dequeuereusablecellwithidentifier:id];        Xmppusercoredatastorageobject *user = [Self.fetchedresultscontroller Objectatindexpath:indexpath];        Show if this friend is concerned about    nsstring *str = [User.jidstr stringbyappendingformat:@ "|%@", user.subscription];        Cell.textLabel.text = str;    Here is a custom method that passes in the section to return Chinese characters via switch. Section relates to whether online    Cell.detailTextLabel.text = [self userStatusWithSection:user.section];        return cell;}

Where subscription is the user's friend mutual bonus situation

If none indicates that the other party has not confirmed//to I am interested in each other//from the other side of concern me//both mutual powder

Again, user.section is the user's state.

Section//0 online//1 leave//2 offline

When a friend is online and the context changes, the scheduler is reordered and the online friends are displayed .

Eight. Delete Friends

The friend's list display interface can add sliding deletions to tableview. (Turn on edit mode)

#pragma mark-******************** open edit mode delete friend-(void) TableView: (UITableView *) TableView Commiteditingstyle: ( Uitableviewcelleditingstyle) Editingstyle Forrowatindexpath: (Nsindexpath *) Indexpath {        if (EditingStyle = = Uitableviewcelleditingstyledelete) {        Xmppusercoredatastorageobject *user = [Self.fetchedresultscontroller Objectatindexpath:indexpath];                 Xmppjid *jid = User.jid;        Next, set up the pop-up window

The way to delete a friend in the Click event of a pop-up window is

[[Sxxmpptools Sharedxmpptools].xmpproster Removeuser:jid];

If you do not see this article in the Dong Platinum Blog Park, please click to view the original

are organizing various details about the information transmission module, interested to be able to pay attention to

XMPP Finishing Notes: User network connections and management of friends

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.