God says, "Offer cannon!" So with XMPP.

Source: Internet
Author: User
Tags file url vcard

I. Import the XMPP framework
  1. Download XMPPFramework Frame

    Github:xmppframework

  2. Import a dependent framework

    • CocoaLumberjack: Log Frame

    • CocoaAsyncSocket: the underlying network framework
      Need to add CFNetwork & Security frame dependencies (XCode 6+ no import required)

    • KissXML: XML parsing framework
      Need to add libxml2.dylib frame dependencies
      You need to specify the following compilation options:
      Other Linker Flags =-LXML2
      Header Search Paths =/usr/include/libxml2

    • libidn

  3. Import folders

    • Authentication
    • Categories
    • Core
    • Utilities
    • Add Dependencies:libresolv.dylib
  4. Import XMPP Extension Framework

    • ExtensionsFolder
    • Import Sample_XMPPFramework.h and rename to:XMPPFramework.h
    • To add a PCH file:
      • Add New File, OtherPCH文件
      • Add #import<UIKit/UIKit.h> to PCH file
      • Set compilation options, Build Settings Precompile prefix Header SelectYes
      • Set compilation options, Build Settings Prefix Header set PCH file name:“项目名/“PCH文件名”
Second, login & logout The steps for user login are as follows:
1. 实例化XMPPStream并设置代理,同时添加代理到工作队列      2. 使用JID连接至服务器,默认端口为5222,JID字符串中需要包含服务器的域名     3. 在完成连接的代理方法中验证用户密码,连接完成后XMPPStream的isConnect属性为YES     4. 在验证代理方法中判断用户是否登录成功        5. 上线或者下线成功后,向服务器发送Presence数据,以更新用户在服务器的状态
The implementation code for each part is as follows:
    • Initialize   xmppstream   and set proxy:

      -(void)   setupxmppstream{_xmppstream = [[Xmppstream alloc] init]; Set agent [_xmppstream adddelegate:self delegatequeue:dispatch_get_global_queue (dispatch_queue_priority_default, 0)];} 

    • Connect to server

      -(void) connecttohost{NSLog (@ "Start connecting to Server");   if (!_xmppstream) {[Self setupxmppstream]; }//Set login user Jid//resource identity user Login client iphone android Xmppjid *myjid = [Xmppjid jidwithuser:@ "AAA" domain:@ "BOURNE-MBP   . Local "resource:@" iphone "];   _xmppstream.myjid = Myjid; Set the server domain name _xmppstream.hostname = @ "bourne-mbp.local";//not only can it be a domain name, but also IP address//Set port if the server port is 5222, you can omit _xmppstream.hostpo   RT = 5222;   Connection Nserror *err = nil; if (![   _xmppstream Connectwithtimeout:xmppstreamtimeoutnone Error:&err]) {NSLog (@ "%@", err); }} 

    • Send password verification after successful connection

      -(void) sendpwdtohost{NSLog (@ "   And then send password authorization ");   Nserror *err = nil;   [_xmppstream authenticatewithpassword:@ "123456" error:&err];   if (err) {NSLog (@ "%@", err); }} 

    • After authorization is successful, send a 在线 message

      #pragma mark  授权成功后,发送"在线" 消息
      -(void) sendonlinetohost{   NSLog (@ "send online message");   Xmpppresence *presence = [xmpppresence presence];   NSLog (@ "%@", presence);   [_xmppstream sendelement:presence];}

        

       
Several proxy methods that need to be implemented
#pragma mark 与主机连接成功
-(void) Xmppstreamdidconnect: (Xmppstream *) sender{    NSLog (@ "Successfully connected to host");    After the host connection succeeds, send the password to authorize    [self sendpwdtohost];}

  


-(void) Xmppstreamdiddisconnect: (Xmppstream *) sender Witherror: (Nserror *) error{
If there is an error, the connection fails NSLog (@ "Disconnect from host%@", error);
}
#pragma Mark Authorized success
-(void) Xmppstreamdidauthenticate: (Xmppstream *) sender{


#pragma Mark's authorization failed
-(void) Xmppstream: (Xmppstream *) sender Didnotauthenticate: (ddxmlelement *) error{
NSLog (@ "Authorization failed%@", error);
}

  

Log Off Login
    • Send 离线 message
    • Disconnect Connection
-(void) logout{    //1. "Send ' offline ' message"    xmpppresence *offline = [xmpppresence presencewithtype:@ "unavailable"];    [_xmppstream Sendelement:offline];    2. Disconnect from server    [_xmppstream disconnect];}

  

Third, registration
    • As with login, first send account to establish connection

    • After the connection is successful, send the registered password

    • After the registration is successful, the framework notifies the agent

Implement the following proxy methods
-(void) Xmppstreamdidregister: (Xmppstream *) Sender {    NSLog (@ "registered successfully");    if (_resultblock) {        _resultblock (bwxmpploginresultsuccessed);    }} -(void) Xmppstream: (Xmppstream *) sender Didnotregister: (ddxmlelement *) Error {    if (_resultblock) {        _ Resultblock (bwxmpploginresultfailure);    }}

  

Iv. User Information

XMPP is module-oriented, and each large kinetic energy belongs to a module that is exposed in the header file (originally annotated) when it is needed.

  1. Working principle:

    After the user information module is added, XMPPFramework框架 user information is automatically retrieved from the server and used CoreData in a local database, with XMPPvCardTempModule access to the data

  2. XMPPFramework.hRemove the comments in front of the following header files:

    // 电子名片模块#import "XMPPvCardTempModule.h"#import "XMPPvCardCoreDataStorage.h"// 头像模块#import "XMPPvCardAvatarModule.h"
  3. Initializing the module

    Add vcard Module _vcardstorage = [Xmppvcardcoredatastorage sharedinstance];_vcard = [[Xmppvcardtempmodule alloc] initwithvcardstorage:_vcardstorage];//Activate [_vcard activate:_xmppstream];//add avatar module _avatar = [[XMPPvCardAvatarModule] Alloc] Initwithvcardtempmodule:_vcard]; [_avatar Activate:_xmppstream];

      

  4. Application

    XMPP provides a way to get personal information directly xmppvcardtemp *myvcard =[wcxmpptool sharedwcxmpptool].vcard.myvcardtemp;//Set the avatar if ( Myvcard.photo) {self.haedView.image = [UIImage ImageWithData:myVCard.photo];} Set Nickname Self.nicknameLabel.text = Myvcard.nickname;

      

Five, friends

Similar to the user Information module, the corresponding friend roster module can be added.

  1. Header file

    // 花名册模块#import "XMPPRoster.h"#import "XMPPRosterCoreDataStorage.h"
  2. Initialization

    Add roster module "get buddy list" _rosterstorage = [[Xmpprostercoredatastorage alloc] Init];_roster = [[Xmpproster alloc] Initwithrosterstorage:_rosterstorage]; [_roster Activate:_xmppstream];

      

  3. Application

    Use CoreData to get data//1. Context "Association to Database Xmpproster.sqlite" Nsmanagedobjectcontext *context = [Wcxmpptool Sharedwcxmpptool]. rosterstorage.mainthreadmanagedobjectcontext;//2.FetchRequest "Check which table" Nsfetchrequest *request = [nsfetchrequest fetchrequestwithentityname:@ "Xmppusercoredatastorageobject"];//3. Set filter and sort//filter Friends of currently logged in user nsstring *jid = [Wcuserinfo Sharedwcuserinfo].jid; Nspredicate *pre = [Nspredicate predicatewithformat:@ "streambarejidstr =%@", jid];request.predicate = pre;// Sort Nssortdescriptor *sort = [Nssortdescriptor sortdescriptorwithkey:@ "DisplayName" ascending:yes]; Request.sortdescriptors = @[sort];//4. Execute request to get data _resultscontrl = [[Nsfetchedresultscontroller alloc] Initwithfetchrequest:request Managedobjectcontext:context Sectionnamekeypath:nil cacheName:nil];_ Resultscontrl.delegate = self; Nserror *err = nil; [_resultscontrl performfetch:&err];if (Err) {Wclog (@ "%@", err);}

      

      • Note: Using NSFetchedResultsController and setting up the proxy, if the contents of the database have changed, this class will automatically notify the agent, you can set the interface data, real-time update.
VI. News
  1. Header file

    • Note: These header files are not in the XMPPFramework.h file and need to be added yourself
    // 消息模块#import "XMPPMessageArchiving.h"#import "XMPPMessageArchivingCoreDataStorage.h"
  2. Initialization

    Add Chat module _msgstorage = [[Xmppmessagearchivingcoredatastorage alloc] init];_msgarchiving = [[Xmppmessagearchiving alloc ] Initwithmessagearchivingstorage:_msgstorage]; [_msgarchiving Activate:_xmppstream];

      

  3. Apply

    //context nsmanagedobjectcontext *context = [Wcxmpptool sharedwcxmpptool].msgstorage.mainthreadmanagedobjectcontext;//Request Object Nsfetchrequest *request = [NSFetchRequest fetchrequestwithentityname:@ "Xmppmessagearchiving_message_coredataobject"];//filtering, sorting//1. The Jid message for the currently logged-on user//2. Friend's Jid message nspredicate *pre = [Nspredicate predicatewithformat:@ "streambarejidstr =%@ and Barejidstr =%@", [Wcuserinfo sha Redwcuserinfo].jid,self.friendjid.bare]; NSLog (@ "%@", pre), request.predicate = pre;//time ascending nssortdescriptor *timesort = [Nssortdescriptor sortdescriptorwithkey: @ "timestamp" ascending:yes];request.sortdescriptors = @[timesort];//Query _resultscontr = [[Nsfetchedresultscontroller Alloc] initwithfetchrequest:request managedobjectcontext:context sectionnamekeypath:nil CacheName:nil]; Nserror *err = nil;//Proxy _resultscontr.delegate = self; [_resultscontr performfetch:&err]; NSLog (@ "%@", _resultscontr.fetchedobjects), if (err) {Wclog (@ "%@", err);} 

Vii. File Transfer (picture, audio)
    1. Principle Analysis

      • Use to base64 convert a file to a string and then XMPPFramework transfer it.
      • Upload the file to the server first, then the file URL through to the XMPPFramework friend, the friend receives and then downloads the file by itself.
  1. Analysis of difficulties

      • You need to XMPPFramework add an information Type field to the ' Data body '.
    Xmppmessage *msg = [xmppmessage messagewithtype:@ "chat" To:self.friendjid];//text plain text//image picture [msg addattributewithname:@ "BodyType" stringvalue:bodytype];//set content [MSG Addbody:text]; NSLog (@ "%@", msg); [[Wcxmpptool Sharedwcxmpptool].xmppstream sendelement:msg];

      

      • Parsing messages based on message type

    "' OBJC

    Xmppmessagearchiving_message_coredataobject *msg = _resultscontr.fetchedobjects[indexpath.row];// Determine whether the picture or plain text nsstring *chattype = [msg.message attributestringvalueforname:@ "BodyType"];if ([Chattype isequaltostring:@ "Image"]) {    //tablet display    [Cell.imageview sd_setimagewithurl:[nsurl URLWithString:msg.body] placeholderimage:[ UIImage imagenamed:@ "Defaultprofilehead_qq"];    Cell.textLabel.text = nil;} else if ([Chattype isequaltostring:@ "text"]) {    //Display message    if ([msg.outgoing boolvalue]) {//        Cell.textLabel.text = Msg.body;    } else{//others        cell.textLabel.text = msg.body;    }    Cell.imageView.image = nil;}

      

```

声明:

The above content is transferred from:

http://www.jianshu.com/p/c7bbbad90639#

God says, "Offer cannon!" So with XMPP.

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.