XMPP Series----------user registration and User login features

Source: Internet
Author: User
Tags addchild

1. Create a new project



2. Import the XMPP framework

Latest XMPP framework: Https://github.com/robbiehanson/XMPPFramework

Drag several folders of XMPP into the project and the files you need are as follows:


and renamed Sample_xmppframework.h to XMPPFramework.h.

Next, import two dependent libraries: Libresolv.dylib and Libxml2.dylib, and then add header search:


Add a PCH file again


Add the following code to the PCH file:

#ifdef __objc__    #import <UIKit/UIKit.h>    #import "XMPPFramework.h" #endif
Then set the project PCH file



$SRCROOT is followed by the project name/pch file name.

After completing the above steps, the project can be compiled successfully!

Now start building the login interface for the project:

First encapsulate an XMPP tool class: Jkxmpptool

. h file

#import <Foundation/Foundation.h> @interface jkxmpptool:nsobject<xmppstreamdelegate> @property ( Nonatomic, Strong) Xmppstream *xmppstream;//module @property (nonatomic, strong) xmppautoping *xmppAutoPing; @property ( Nonatomic, Strong) Xmppreconnect *xmppreconnect, @property (nonatomic, assign) BOOL  xmppneedregister; @property ( nonatomic, copy)   NSString *mypassword;+ (instancetype) sharedinstance;-(void) Loginwithjid: (Xmppjid *) JID Andpassword: (NSString *) password;-(void) Registerwithjid: (Xmppjid *) JID Andpassword: (NSString *) password; @end
. m file

#import "JKXMPPTool.h" @implementation jkxmpptoolstatic jkxmpptool *_instance;+ (instancetype) sharedinstance{static    dispatch_once_t Oncetoken;    Dispatch_once (&oncetoken, ^{_instance = [Jkxmpptool new];        }); return _instance;}                -(Xmppstream *) xmppstream{if (!_xmppstream) {_xmppstream = [[Xmppstream alloc] init];        The socket connection should know the HOST port and connect [Self.xmppstream Sethostname:kxmpp_host];        [Self.xmppstream Sethostport:kxmpp_port]; Why the AddDelegate? Because Xmppframework uses a large number of multicast proxy multicast-delegate, the agent is generally 1 to 1, but this multicast proxy is a one-to-many, and can add or remove at any time [Self.xmppstream adddelegate:                Self Delegatequeue:dispatch_get_main_queue ()]; Add a function module//1.autoping send a stream:ping if you want to indicate that you are active, you should return a pong _xmppautoping = [[Xmppautoping alloc] init]        ;                All module modules must activate active [_xmppautoping Activate:self.xmppStream]; Autoping because it will periodically send pings, ask the other side to return pong, so this time we need to set [_xmppautoping sETPINGINTERVAL:1000];        It is not just the server that responds; if it is a normal user, it will respond to [_xmppautoping Setrespondstoqueries:yes]; This process is C---->s; observe S--->c (needs to be set on the server)//2.autoreconnect automatically reconnect, when we are disconnected, automatically reconnected up, and the last information automatically added to _x        Mppreconnect = [[Xmppreconnect alloc] init];        [_xmppreconnect Activate:self.xmppStream];    [_xmppreconnect Setautoreconnect:yes]; } return _xmppstream;} -(void) Loginwithjid: (Xmppjid *) JID Andpassword: (NSString *) password{//1. Set up a TCP connection//2. Bind my own JID to this TCP connection//3 . Authentication (Login: Verify JID and password is correct, encryption method cannot be sent in clear text)--(attendance: How to tell the server I live, and I have to go online status//This sentence will be sent after Xmppstream XML <message from= "JID"    > [Self.xmppstream Setmyjid:jid];    Self.mypassword = password;    Self.xmppneedregister = NO; [Self.xmppstream Connectwithtimeout:xmppstreamtimeoutnone error:nil];} The registration method does not call the Auth method-(void) Registerwithjid: (Xmppjid *) JID Andpassword: (NSString *) password{[Self.xmppstream Setmyjid:    JID];    Self.mypassword = password; Self.xmppneedregister =YES; [Self.xmppstream Connectwithtimeout:xmppstreamtimeoutnone error:nil];} -(void) goonline{//Send a <presence/> default value avaliable online means that the server receives an empty presence would think this xmpppresence *presence = [XMPPPR        Esence presence]; Send a more complex attendance status//<presence type= "avaliable" >//<status> I'm busy </status>//&LT;SHOW&G t;xa</show>//</presence> [presence Addchild:[ddxmlnode elementwithname:@ "status" stringvalue:@ "I am now very    Busy "]);        [Presence Addchild:[ddxmlnode elementwithname:@ "show" stringvalue:@ "XA"]; [Self.xmppstream sendelement:presence];} #pragma mark ===== Xmppstream delegate =======//socket Connection established successfully-(void) Xmppstream: (Xmppstream *) Sender Socketdidconnect: ( Gcdasyncsocket *) socket{NSLog (@ "%s", __func__);}    This is the successful initialization of the XML stream-(void) Xmppstreamdidconnect: (Xmppstream *) sender{NSLog (@ "%s", __func__); Anonymous login randomly generates a username and Jid, which is randomly generated in the server's memory and will not be written to the server's data table//To prevent the client from logging on anonymously, the server has a policy close anonymous//[Self.xmppstream Authenticatea Nonymously:nil];    if (self.xmppneedregister) {[Self.xmppstream registerWithPassword:self.myPassword error:nil];    } else {[Self.xmppstream authenticateWithPassword:self.myPassword error:nil]; }}-(void) Xmppstreamdiddisconnect: (Xmppstream *) sender Witherror: (Nserror *) error{NSLog (@ "%s", __func__);} Login failed-(void) Xmppstream: (Xmppstream *) sender Didnotauthenticate: (ddxmlelement *) error{NSLog (@ "%s", __func__);}        Login Success-(void) Xmppstreamdidauthenticate: (Xmppstream *) sender{NSLog (@ "%s", __func__);        [Self goonline]; [[Nsnotificationcenter Defaultcenter] postnotificationname:klogin_success object:nil];} @end

Then the login function:

The action for the login button is as follows:

#pragma mark-click event/** logon event */-(ibaction) Loginclick: (ID) Sender {    NSString *username = _usernamefield.text;
   nsstring *password = _passwordfield.text;        NSString *message = nil;    if (username.length <= 0) {        message = @ "User name not filled in";    } else if (password.length <= 0) {        message = @ "Password not filled in"; c7/>}        if (Message.length > 0) {        Uialertview *alertview = [[Uialertview alloc] Initwithtitle:nil message: Message Delegate:nil cancelbuttontitle:@ "I Know" otherbuttontitles:nil];        [Alertview show];    } else {[        [jkxmpptool sharedinstance] Loginwithjid:[xmppjid jidwithuser:username domain:@ "im.joker.cn" resource:@ "IOS"] andpassword:password];}    }
returning a successful login message with a notification

-(void) loginsuccess{    NSLog (@ "loginsuccess");        [Self performseguewithidentifier:@ "Loginsegue" sender:self];}

Then realize the function of registering:


-(Ibaction) Registaction: (ID) Sender {nsstring *username = _usernamefield.text;    NSString *password = _passwordfield.text;        NSString *confirm = _confirmfield.text;    NSString *message = nil;    if (username.length <= 0) {message = @ "username not filled in";    } else if (password.length <= 0) {message = @ "Password not filled in";    } else if (confirm.length <= 0) {message = @ "Confirmation password not filled in"; } if (Message.length > 0) {uialertview *alertview = [[Uialertview alloc] Initwithtitle:nil Message:messa        GE Delegate:nil cancelbuttontitle:@ "I Know" otherbuttontitles:nil];    [Alertview show]; } else if (![        Password Isequaltostring:confirm]) {message = @ "Password is inconsistent with confirmation password"; Uialertview *alertview = [[Uialertview alloc] initwithtitle:nil message:message delegate:nil cancelButtonTitle:@ "I know."        Otherbuttontitles:nil];    [Alertview show]; } else {[[Jkxmpptool sharedinstance] Registerwithjid:[xmppjid jidwithuser:username domain:@ ' im.joker.cn ' resource:@ "IOS"] andpassword:password]; }}
Since registration does not require authentication, registration returns BOOL results directly, so the connection Broker method is improved:

This is the successful initialization of the XML stream-(void) Xmppstreamdidconnect: (Xmppstream *) sender{    NSLog (@ "%s", __func__);    if (self.xmppneedregister) {        BOOL result = [Self.xmppstream registerWithPassword:self.myPassword error:nil];        NSNumber *number = [NSNumber numberwithbool:result];                [[Nsnotificationcenter Defaultcenter] Postnotificationname:kregist_result object:number];            } else {        [self.xmppstream authenticateWithPassword:self.myPassword error:nil];}    }

: Click to download

GitHub Address: Https://github.com/Joker-King/ChatDemo




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

XMPP Series----------user registration and User login features

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.