Use JSQMessagesViewController to create an iOS chat App-Part 1

Source: Internet
Author: User
Tags install cocoapods

Use JSQMessagesViewController to create an iOS chat App-Part 1

In this tutorial, I will introduce how to create a simple iOS chat App (using swift and Syncano ). We will start with the most basic functions-sending and receiving messages, saving the messages to the server, and then entering the user account and authentication topics.

We will use Syncano and its iOS Library at the backend, and JSQMessagesViewController Library at the front end.

In the first part, we will include creating a new project, adding JSQMessagesViewController (and then displaying some test messages above ). In the second part, we save the data to the server and synchronize it in real time (when the new message is saved to the database, it is immediately displayed without any refresh operations ). Finally, in the third part, we will add the user authentication function-register, log on, and display the correct information to the user.

Create a new project

To create a new project. Open Xcode and create a Single View Application project. Enter SyncanoChat for the project name. Select Swift as the language.

Install CocoaPods

To use the Syncano iOS library and JSQMessagesViewController, we must use CocoaPods.

Install CocoaPods

If you have not installed CocoaPods, you need to install it on the terminal:

Sudo gem install cocoapods

Enter the password and press Enter. Wait until the installation is complete.

Import to Warehouse

In the terminal program, enter the created project directory, for example:

Cd ~ /Path/to/my/project/SyncanoChat

Initialize Cocoapods:

Pod init

Edit the Podfile file:

Open Podfile

Import the required library in the file (between the target 'syncanopic' do and end), uncomment the use_frameworks line, or directly replace the file with the following content:

# Uncomment this line to define a global platform for your project# platform :ios, '8.0'# Uncomment this line if you're using Swiftuse_frameworks!target 'SyncanoChat' dopod 'syncano-ios'pod 'JSQMessagesViewController'endtarget 'SyncanoChatTests' doendtarget 'SyncanoChatUITests' doend

Save the file, close the Text Editor (we will not modify this file again), and enter:

Pod install

When the command execution is complete, close Xcode and open the Workspace file:

Open SyncanoChat. xcworkspace

Run the program and make sure that no errors occur!

Add the Objective-C bridging header file

This step is not required. If you have not uncommented use_frameworks! One line. If so, go to the next step.

For some reason, you cannot use the use_frameworks of Cocoapods! Feature (dynamic library) or you would rather use static library, you must add a bridge header file.

Use menu:

File-> New-> File

Select Cocoa class, click Next, and enter a class name (we will not use this class), such as Test, change the language to Objective-C, and click Next.

Select Yes If You Want To create an Objective_C bridging header.

This will create 2 files by default. Select the file in Xcode and delete it.

When you ask whether to put the two files in the recycle bin, Move to Trash.

Note that while creating a class file, Xcode also creates a bridge header file for the SyncanoChat-Bridging-Header.h. Open the file and add two lines:

#import 
  
   #import 
   
  

Save the file and re-compile the project. Now, you can use these two libraries in Swift code.

Message Controller subclass JSQMessagesViewController

Now we start to use JSQMessagesViewController. In the XCode project navigation window, open ViewController. swift.

Currently, it is also a subclass of UIViewController and changed to the subclass of JSQMessagesViewController:

import UIKitclass ViewController: JSQMessagesViewController {//...// rest of the class//...}

If you do not use a bridge header file, you may need to add two import statements under import UIKit, as shown below:

import UIKitimport JSQMessagesViewControllerimport syncano_ios

Compile the project and confirm that Xcode can connect to all files and recognize the JSQMessagesViewController class.

Add attribute

Add several variables to store message data and UI components:

Messages: used to store received and sent messages. Because every time we send or receive a message, this message is added to messages, so it is variable. IncomingBubble: JSQMessagesViewController will use it to define the background image for receiving messages. We will not change it, so it is defined as a constant. OutgoingBubble: JSQMessagesViewController will use it to define the background image of the sent message. We will not change it, so it is defined as a constant.

Add the following attributes:

    let incomingBubble = JSQMessagesBubbleImageFactory().incomingMessagesBubbleImageWithColor(UIColor(red: 10/255, green: 180/255, blue: 230/255, alpha: 1.0))    let outgoingBubble = JSQMessagesBubbleImageFactory().outgoingMessagesBubbleImageWithColor(UIColor.lightGrayColor())    var messages = [JSQMessage]()
Add Test message

Before we introduce Syncano, we add some test data for display.

Add a new method in ViewController:

func reloadMessagesView() {   self.collectionView?.reloadData()}

This method is used to refresh the message list. We encapsulate the load list as a separate method.

Add an extension to ViewController. swift:

//MARK - Setupextension ViewController {    func addDemoMessages() {        for i in 1...10 {            let sender = (i%2 == 0) ? "Server" : self.senderId            let messageContent = "Message nr. \(i)"            let message = JSQMessage(senderId: sender, displayName: sender, text: messageContent)            self.messages += [message]        }        self.reloadMessagesView()    }    func setup() {        self.senderId = UIDevice.currentDevice().identifierForVendor?.UUIDString        self.senderDisplayName = UIDevice.currentDevice().identifierForVendor?.UUIDString    }}

The setup method is used to specify the unique device ID to senderID and senderDisplayName. Both are required by JSQMessagesViewController and used to differentiate who sends and who the message is sent.

Call these two methods in the viewDidLoad method:

    override func viewDidLoad() {        super.viewDidLoad()        // Do any additional setup after loading the view, typically from a nib.        self.setup()        self.addDemoMessages()    }

Run the App. It does not display anything, but the test message we use to display is ready.

Implement JSQMessagesViewController Protocol

We must implement several methods, especially the JSQMessagesCollectionViewDataSource protocol method.

Add an extension to ViewController. swift:

//MARK - Data Sourceextension ViewController {    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {        return self.messages.count    }    override func collectionView(collectionView: JSQMessagesCollectionView!, messageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageData! {        let data = self.messages[indexPath.row]        return data    }    override func collectionView(collectionView: JSQMessagesCollectionView!, didDeleteMessageAtIndexPath indexPath: NSIndexPath!) {        self.messages.removeAtIndex(indexPath.row)    }    override func collectionView(collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageBubbleImageDataSource! {        let data = messages[indexPath.row]        switch(data.senderId) {        case self.senderId:            return self.outgoingBubble        default:            return self.incomingBubble        }    }    override func collectionView(collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageAvatarImageDataSource! {        return nil    }}

These methods are used to tell JSQMessagesViewController:

-How many messages are displayed (that is, the number of messages in the messages array)-which messages are displayed for each row?-What to do when a message is deleted (removed from the messages array) -What kind of bubble is displayed for each message (if it is a bubble image indicating "sent message", otherwise it is a bubble image indicating "received message) -What to display on the Avatar (Nil is returned here, that is, no Avatar is displayed) run the App, and now it displays the Test message! If you click the button in the toolbar, the App will crash. ### To handle button events to solve the App crash, you must implement two methods: one for processing the media button event on the left and the other for processing the send button event on the right. Add an extension to ViewController. swift: ''' swift // MARK-Toolbarextension ViewController {override func didPressSendButton (button: UIButton !, WithMessageText text: String !, SenderId: String !, SenderDisplayName: String !, Date: NSDate !) {Let message = JSQMessage (senderId: senderId, senderDisplayName: senderDisplayName, date: date, text: text) self. messages + = [message] self. finishSendingMessage ()} override func didPressAccessoryButton (sender: UIButton !) {}}

When you click send, we add the input content to messages and refresh the UI. In the didPressAccessoryButton (_) method, we do nothing, but let the App no longer crash.

Summary

You have completed all the interfaces of a chat App. You can send messages or see messages sent by others.

In the second part, we continue to learn how to deal with Syncano, including saving messages to the server and Real-Time Message synchronization.

You can download the source code from GitHub.

If you have any questions, please tweet me.

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.