xmpp-ios-Get friends List, chat list, chat

Source: Internet
Author: User

typedef enum {// enum for sending message type

Text

Image

Audio

} Msgtype;


#import "XMPPData.h" #import "XMPPFramework.h" @interface xmppdata () <xmppstreamdelegate,xmpprosterdelegate, Nsfetchedresultscontrollerdelegate> @property (strong,nonatomic) Xmppstream *xmppstream; @property (Assign, nonatomic) BOOL isregister; @property (strong,nonatomic) Nsstring*user,*pwd,*hostname,*domain; @property (Assign, nonatomic) UInt16 Port, @property (strong,nonatomic) xmpprostercoredatastorage * rosterstorage;//Roster Storage @property ( strong,nonatomic) Xmpproster * rostermodule;//Roster Module @property (strong,nonatomic) xmppmessagearchivingcoredatastorage *msgstorage;//message store @property (strong,nonatomic) xmppmessagearchiving * msgmodule;//message Module @property (strong,nonatomic) Nsfetchedresultscontroller *fetfriend;//Check your friend's Fetch@property (strong,nonatomic) Nsfetchedresultscontroller * fetmsgrecord;//Query Message fetch@end@implementation xmppdata//start connection to chat server-(BOOL) Connectwithusername: (nsstring*) Username Andpwd: (nsstring*) pwd andhostname: (nsstring*) hostname anddomain: (nsstring*) domain Andhostport: (UInt16) port AndisregiSter: (BOOL) isregister{self.hostname = HostName;    Self.port = port;    Self.domain = domain;    Self.user = Username;    Self.pwd = pwd;    Self.isregister = Isregister;    Self.xmppstream = [[Xmppstream alloc] init];    Set agent [Self.xmppstream adddelegate:self delegatequeue:dispatch_get_global_queue (0, 0)];    Set the chat server address self.xmppstream. hostName = HostName;    Setting the chat server port by default is 5222 Self.xmppStream.hostPort = port;    Set Jid is user name Xmppjid *jid = [Xmppjid jidwithuser:username domain:domain resource:@ "test"];    Self.xmppStream.myJID = Jid;    Nserror * error = NIL;    Verify connection [Self.xmppstream Connectwithtimeout:xmppstreamtimeoutnone error:&error];        if (Error) {NSLog (@ "Connection failed:%@", error);    return NO;        } else {//register all modules [self activemodules];    return YES;    }}//Activation related module-(void) activemodules{//1. Roster storage Object self.rosterstorage = [Xmpprostercoredatastorage sharedinstance]; 2. Roster module Self.rostermodule = [[Xmpproster ALloc] initWithRosterStorage:self.rosterStorage];    3. Activate this module [Self.rostermodule Activate:self.xmppStream];        4. Add Roster Agent [Self.rostermodule adddelegate:self delegatequeue:dispatch_get_main_queue ()];    1. Message Store Object self.msgstorage = [Xmppmessagearchivingcoredatastorage sharedinstance];    Self.msgmodule = [[Xmppmessagearchiving alloc] initWithMessageArchivingStorage:self.msgStorage];    [Self.msgmodule Activate:self.xmppStream];    [Self.msgmodule adddelegate:self Delegatequeue:dispatch_get_main_queue ()];    }//downline-(void) logout{//1. User downline NSLog (@ "logout user");    Xmpppresence *presene=[xmpppresence presencewithtype:@ "unavailable"];    Set the downline status [_xmppstream Sendelement:presene]; 2. Disconnect [_xmppstream disconnect];} Add Friend-(BOOL) Addfriend: (nsstring*) friendname{Xmppjid * Friendjid = [Xmppjid jidwithstring:[nsstring stringWithFormat    : @ "%@@%@", Friendname,self.domain]];    [Self.rostermodule Subscribepresencetouser:friendjid]; return YES;} Delete Friend-(BOOL) DeletefriEnd: (nsstring*) friendname{Xmppjid * Friendjid = [Xmppjid jidwithstring:[nsstring stringwithformat:@ "%@@%@", friendNam    E,self.domain]];    [Self.rostermodule Removeuser:friendjid];    return YES; }//Get Friends List-(nsarray*) getfriends{nsmanagedobjectcontext *context =    Self.rosterStorage.mainThreadManagedObjectContext;        Nsfetchrequest *request = [[Nsfetchrequest alloc] initwithentityname:@ "Xmppusercoredatastorageobject"];        Filter this user's friend nsstring *userinfo = [NSString stringwithformat:@ "%@@%@", Self.user,self.domain];    NSLog (@ "userinfo =%@", userinfo);    Nspredicate *predicate = [Nspredicate predicatewithformat:@ "streambarejidstr =%@", userinfo];        Request.predicate = predicate;    Sort Nssortdescriptor * sort = [Nssortdescriptor sortdescriptorwithkey:@ "DisplayName" ascending:yes];        Request.sortdescriptors = @[sort]; Self.fetfriend = [[Nsfetchedresultscontroller alloc] Initwithfetchrequest:request managedobjectcontext:context Sectionnamekeypath:nilCachename:nil];    Self.fetFriend.delegate = self;    Nserror *error;    [Self.fetfriend performfetch:&error]; The returned array is the Xmppusercoredatastorageobject *obj type//name called Obj.displayname NSLog (@ "%lu", (unsigned long) self.fetFriend.fetc    Hedobjects.count); return self.fetFriend.fetchedObjects;} Database changed-(void) Controller: (Nsfetchedresultscontroller *) controller didchangeobject: (ID) anobject Atindexpath: (    Nsindexpath *) Indexpath Forchangetype: (nsfetchedresultschangetype) type Newindexpath: (Nsindexpath *) newIndexPath{    Nsmanagedobject *obj = AnObject; if ([obj Iskindofclass:[xmppmessagearchiving_message_coredataobject class]]) {NSLog (@ "<span style=" Font-fami Ly:arial, Helvetica, Sans-serif;    > Chat information about the database changes </span> "); }
    else NSLog (@ "database has changed");} Chat with a friend-(BOOL) Talktofriend: (nsstring*) friendsname andmsg: (nsstring*) msg andmsgtype: (msgtype) msgt{Xmppjid *toFri end = [Xmppjid jidwithuser:friendsname domain:self.domain resource:@ "A"];//resource arbitrarily, currently does not affect xmppmessage * message = [[    Xmppmessage alloc] initwithtype:@ "chat" to:tofriend];//chat type is the normal chat type [message addbody:msg];    [Message addattributewithname:@ "Msgtype" INTVALUE:MSGT];    [Self.xmppstream Sendelement:message]; return YES;} Get a chat record with a friend-(nsarray*) GetRecords: (nsstring*) friendsname{//All accounts and everyone's chats are in the same database so write query conditions Nsmanagedobje    Ctcontext *context = Self.msgStorage.mainThreadManagedObjectContext; Nsfetchrequest *request = [[Nsfetchrequest alloc] initwithentityname:@ "Xmppmessagearchiving_message_coredataobject"    ];    NSString *userinfo = [NSString stringwithformat:@ "%@@%@", Self.user,self.domain];    NSString *friendinfo = [NSString stringwithformat:@ "%@@%@", Friendsname,self.domain]; Nspredicate *predicate= [Nspredicate predicatewithformat:@ "streambarejidstr =%@ and Barejidstr =%@", Userinfo,friendinfo];        Request.predicate = predicate;    Nssortdescriptor * sort = [Nssortdescriptor sortdescriptorwithkey:@ "timestamp" ascending:yes];    Request.sortdescriptors = @[sort]; Self.fetmsgrecord = [[Nsfetchedresultscontroller alloc] Initwithfetchrequest:request managedobjectcontext:context    Sectionnamekeypath:nil Cachename:nil];    Self.fetMsgRecord.delegate = self;    Nserror *error; [Self.fetmsgrecord performfetch:&error];//returns the value type Xmppmessagearchiving_message_coredataobject return Self.fetMsgRecord.fetchedObjects;}    Connection Successful agent function-(void) Xmppstreamdidconnect: (Xmppstream *) sender{NSLog (@ "Connection succeeded");        if (self.isregister) {nserror* error = nil;        [Sender RegisterWithPassword:self.pwd error:&error];        if (Error) {NSLog (@ "Registration failed 1,%@", error);        }} else {nserror *error = nil; [Sender AuthenticateWithPassword:self.pwd error:&error];        if (Error) {NSLog (@ "validation failed 1,%@", error); }}//Connection Failed agent function-(void) Xmppstreamdiddisconnect: (Xmppstream *) sender Witherror: (Nserror *) error{NSLog (@ "Connection failed,%@", Erro R);}    Verify Success Agent Function-(void) Xmppstreamdidauthenticate: (Xmppstream *) sender{NSLog (@ "verify success"); 4. Login successful online [self.xmppstream sendelement:[xmpppresence presence]];//user Online}//authentication failed agent function-(void) Xmppstream: (Xmppstream * Sender Didnotauthenticate: (ddxmlelement *) error{NSLog (@ "Verification failed,%@", error);} Registered Success Agent function-(void) Xmppstreamdidregister: (Xmppstream *) sender{NSLog (@ "registered successfully");} Registration failed agent function-(void) Xmppstream: (Xmppstream *) sender Didnotregister: (ddxmlelement *) error{NSLog (@ "registration failed,%@", error);} Received Friend request agent function-(void) Xmpproster: (Xmpproster *) sender Didreceivepresencesubscriptionrequest: (xmpppresence *) presence    {NSString * presencetype = [presence type];    NSLog (@ "Presencetype =%@", presencetype);    Xmppjid * Fromjid = Presence.from;  if ([Presencetype isequaltostring:@ "Subscribe"]) {//is a subscription request directly through      [Self.rostermodule Acceptpresencesubscriptionrequestfrom:fromjid Andaddtoroster:yes]; }}-(void) Xmpproster: (Xmpproster *) sender Didreceiverosteritem: (ddxmlelement *) item{nsstring *subscription = [item att    ributestringvalueforname:@ "Subscription"];    NSLog (@ "%@", subscription); if ([Subscription isequaltostring:@ "both"]) {NSLog (@) The two sides become friends!    "); }} @end

Demo

The above is the main content of the code

xmpp-ios-Get friends List, chat list, chat

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.