Using XMPPFramework for instant communication in iOS Development (2)

Source: Internet
Author: User

Using XMPPFramework for instant communication in iOS Development (2)
Let's start with today's topic. Today, You need to log on to the previous website to obtain a list of friends, chat (send text, emoticons, images, sounds, and other functions), and recent contacts. At the beginning of the blog, let's take a few pictures to introduce the functions, and then give the implementation of the core code. I. Function Module 1. the process of logging on to and getting a friend list is to connect to Openfire using XMPPFramework. If a user logs on, the user's JID and password are automatically connected from UserDefault, if you have not logged in, log in. The list of friends is also obtained through the Roster in XMPPFramework. Run the following command: 2. A friend clicks the chat page. If the picture or sound is sent during the chat, it is first stored on the server, and the server returns the storage path and then sends the URL to the recipient, the receiver downloads (1) the sent text, converts the text to an attribute string, converts it to NSData, and finally converts it to a string and places it in the Body of the Message for sending, the following is a test done by Spark on the receiving end. (2) Send an image and send the storage path of the image to the recipient so that the recipient can download the image from the server. As shown in the following figure: (3) The sending sound is the same as the image sending URL, as shown in the following figure: 2. The above part of the code implementation is allowed. It is not difficult to see the functional points. The figure shows the implementation of the core code. 1. Use preparations before XMPPFramework to obtain XmppStream and the components to be activated, and add code in AppDelegate. When xmppStream is used later, it must be obtained through AppDelegate. The following code is in AppDelegate. initialize related components in m. The Code is as follows (1) instantiate XMPPStream // create xmppstream self. xmppStream = [[XMPPStream alloc] init]; (2) create a reconnection component, and activate 1 in xmppStream // create rewrite connection component 2 xmppReconnect = [[XMPPReconnect alloc] init]; 3 // make the component take effect 4 [xmppReconnect activate: self. xmppStream]; (3) create the content of the message. The received message is saved in the local database. We obtain it from the database when displaying the message. When initializing the message component, you must specify the storage policy. Generally, you can choose CoreData or memory. After the Save policy is specified, the Message is instantiated to be associated with the Save policy. After that, the Message needs to be activated in XMPPStream and the context of CoreData needs to be obtained. The Code is as follows: Copy code 1 // create a message storage policy (rule, required) 2 messageStorage = [XMPPMessageArchivingCoreDataStorage sharedInstance]; 3 // create a message storage component using the message storage policy. 4 xmppMessageArchiving = [[XMPPMessageArchiving alloc] handle: messageStorage]; 5 // make the component take effect. 6 [xmppMessageArchiving activate: self. xmppStream]; 7 // extract the coreData context of the message storage component 8 self. xmppManagedObjectContext = messageStorage. mainThreadManagedObjectContext; copy the code (4) and obtain friends through initialization. List of related components and specify the Save policy, and the above Code steps are very similar. It can also be seen that the component initialization steps in XMPPFramework are similar. The following code automatically retrieves the roster: Copy code 1 xmppRosterStorage = [[XMPPRosterCoreDataStorage alloc] init]; 2 xmppRoster = [[XMPPRoster alloc] initWithRosterStorage: xmppRosterStorage]; 3 // automatically obtain the user list 4 xmppRoster. autoFetchRoster = YES; 5 xmppRoster. autoAcceptKnownPresenceSubscriptionRequests = YES; 6 7 [xmppRoster activate: self. xmppStream]; 8 self. xmppRosterManagedObjectContext = xmppRosterStorage. mainThreadManagedObjectConte Xt; copy Code 2. when logging on to the login module, the user enters the JID and Password, then connects to the server and verifies the Password. If the authentication succeeds, the user jumps to the friends list to access the Controller, store the JID and Password in UserDefaults to facilitate the next automatic connection. The following code is the LoginViewController. m): (1 ). get XMPPStream through the Application proxy and register the callback. The Code is as follows: Copy code 1-(void) initXmpp 2 {3 // get the xmppSteam of the Application (obtained through the singleton in the Application) 4 UIApplication * application = [UIApplication sharedApplication]; 5 id delegate = [application delegate]; 6 self. xmppStream = [delegate xmppStream]; 7 8 // registration callback 9 [self. xmppStream addDelegate: self delegateQueue: dispatch_get_main_queue ()]; 10} copy the code (2 ). create a JID Connection Service Copy code 1 // connect to server 2-(void) xmppConnect 3 {4 if (! [Self. userNameTextFiled. text isw.tostring: @ ""] & self. userNameTextFiled. text! = Nil) 5 {6 // 1. create JID 7 XMPPJID * jid = [XMPPJID jidWithUser: self. userNameTextFiled. text domain: MY_DOMAIN resource: @ "iPhone"]; 8 9 // 2. add JID to xmppSteam 10 [self. xmppStream setMyJID: jid]; 11 12 // connection server 13 NSError * error = nil; 14 [self. xmppStream connectWithTimeout: 10 error: & error]; 15 if (error) 16 {17 NSLog (@ "connection error: % @", [error localizedDescription]); 18} 19 20} 21 else22 {23 UIAlertView * alter = [[UIAlert View alloc] initWithTitle: @ "prompt" message: @ "username cannot be blank" delegate: nil cancelButtonTitle: @ "cancel" otherButtonTitles: nil]; 24 [alter show]; 25} 26} copy the code (3 ). the authentication password is required after the connection is established. The Code is as follows: Copy code 1 // callback 2-(void) xmppStreamDidConnect :( XMPPStream *) sender 3 {4 if (! [Self. passwordTextFiled. text is0000tostring: @ ""] & self. passwordTextFiled. text! = Nil) 5 {6 // authentication username and password after successful connection 7 NSError * error = nil; 8 [self. xmppStream authenticateWithPassword: self. passwordTextFiled. text error: & error]; 9 if (error) 10 {11 NSLog (@ "authentication error: % @", [error localizedDescription]); 12} 13} 14 else15 {16 UIAlertView * alter = [[UIAlertView alloc] initWithTitle: @ "prompt" message: @ "password cannot be blank" delegate: self cancelButtonTitle: @ "cancel" otherButtonTitles: nil]; 17 [alter show]; 18} 19} copy code (4) Code 1 // callback 2-(void) xmppStreamDidAuthenticate after successful password authentication (XMPPStream *) sender 3 {4 NSLog (@ "Login successful "); 5 6 // enter userDefault 7 NSUserDefaults * userDefult = [NSUserDefaults standardUserDefaults] with the password; 8 [userDefult setObject: self. userNameTextFiled. text forKey: @ "username"]; 9 [userDefult setObject: self. passwordTextFiled. text forKey: @ "password"]; 10 11 // sets the online status 12 XMPPPresence * pre = [XMPPPresence pres Ence]; 13 [self. xmppStream sendElement: pre]; 14 15 UIStoryboard * storybard = [UIStoryboard storyboardWithName: @ "Main" bundle: [NSBundle mainBundle]; 16 UIViewController * viewController = [storybard category: @ "mainController"]; 17 [self presentViewController: viewController animated: YES completion: ^ {18}]; 19} copy the code (5) callback after password authentication failure 1 // callback for authentication failure 2-(void) xmppStream: sender didNotA Uthenticate :( DDXMLElement *) error3 {4 NSLog (@ "authentication failed"); 5} (6), the second login automatic connection code: copy code 1 // if you have logged on, enter the password and log on to nsuserults ults * userDefult = [NSUserDefaults standardUserDefaults]; 3 4 NSString * userName = [userDefult objectForKey: @ "username"]; 5 NSString * password = [userDefult objectForKey: @ "password"]; 6 NSLog (@ "% @, % @", userName, password); 7 if (userName! = Nil & password! = Nil &&! [UserName isEqualToString: @ ""] &! [Password isEqualToString: @ ""]) 8 {9 self. userNameTextFiled. text = userName; 10 self. passwordTextFiled. text = password; 11 [self xmppConnect]; 12} copy code 3. the XMPPFramework code for getting the friend list will use the previously registered Roster content in the Code for getting the user list, because the storage policy we specify when instantiating the Roster is saved using CoreData and the friends list is automatically obtained. Therefore, in TableViewController that obtains the friend list, you only need to use CoreData to obtain the friend list. The core code for getting a friend list is as follows: (1) obtain the context of the Roster, used to obtain data stored in the corresponding Roster object 1 // obtain the context of Roster 2 UIApplication * application = [UIApplication sharedApplication]; 3 id delegate = [application delegate]; 4 self. xmppRosterManagedObjectContext = [delegate xmppRosterManagedObjectContext]; (2 ). obtain the FetchRequst object, specify the CoreData object class, and add a sorting rule. The Code is as follows: copy code 1 // obtain data from CoreData 2 // obtain FetchRequest entity 3 NSFetchRequest * request = [NSFetchReques T alloc] initWithEntityName: NSStringFromClass ([strong class])]; 4 // Add the sorting rule 5 NSSortDescriptor * sortD = [NSSortDescriptor handler: @ "jidStr" ascending: YES]; 6 [request setSortDescriptors: @ [sortD]; copy the code (3 ). get FetchedResultController and register the callback to automatically refresh TableView. The Code is as follows: 1 // get FRC2 self. fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest: request ManagedObjectContext: self. xmppRosterManagedObjectContext sectionNameKeyPath: nil cacheName: nil]; 3 self. fetchedResultsController. delegate = self; (4) get stored content copy code 1 2 // get content 3 NSError * error; 4; 5 if (! [Self. fetchedResultsController initialize mfetch: & error]) 6 {7 NSLog (@ "% s % @" ,__ FUNCTION __, [error localizedDescription]); 8}

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.