Use JSQMessagesViewController to create an iOS chat App-Part 1

Source: Internet
Author: User

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 ).

In the first part, we created a new project and added a JSQMessagesViewController (then some test messages are displayed on it ).

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 ).

If you miss the first part, you can read it here. You can start from the first part, or download the first part of the code and then start.

Note that CocoaPods is used in this project. If you have not used CocoaPods, you do not know how to install it. For more information, see section 1.

Add Syncano

Next is an exciting step-actually sending messages to the background and receiving messages from others.

Register Syncano

If you do not have an account yet, please register here-it only takes 10 seconds for you to provide an email address and password.

Configure Syncano

Log on to your Syncano account.

If you do not have a Syncano instance (an instance is a project) or you want to use an empty instance, you can create a new instance:

Remember your instance name and select it.

Create a new class to save all messages using this class: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxwPjxpbWcgYWx0PQ = "" src = "http://www.bkjia.com/uploads/allimg/160303/03562522Y-1.png" title = "\"/>

Enter a Message for the class name and set the following fields:

Text: String senderid: String attachment: File

We also need to add a channel to synchronize data in real time.

Go to the Channels page and add a channel. The channel name is Messages and other permissions is set to publish.


Finally, create an API key to connect to the database. Enter the description field as needed, but the Ignore ACL must be set to True (the switch ON the right side is pulled to the ON position ).


After the key is set, write down the key -- we will use it later.

Add Syncano to the Project

First, we need a Syncano object that specifies the Instance name and API key to be used in the connection. This object is shared by all connections. A Channel object is also required for data synchronization. Add them to ViewController:

let syncanoChannelName = "messages"

class ViewController: JSQMessagesViewController {

    let syncano = Syncano.sharedInstanceWithApiKey(YOUR_API_KEY, instanceName: YOUR_INSTANCE_NAME)
    let channel = SCChannel(name: syncanoChannelName)

    //...
}

Replace YOUR_API_KEY and YOUR_INSTANCE_NAME with the values you noted down earlier. If your channel name is different from mine, replace it.

Download and send messages

Before starting interaction with Syncano, we also need to define a class to map the class we created in the Dashboard.

Create a Cocoa class in Xcode. The class name is "Message" and inherits SCDataObject. The language is Swift:

Edit Message. swift:

import UIKit
import syncano_ios

class Message: SCDataObject {
    var text = ""
    var senderId = ""
    var attachment : SCFile?

    override class func extendedPropertiesMapping() -> [NSObject: AnyObject] {
        return [
            "senderId":"senderid"
        ]
    }
}

We define the class as the class defined in Dashboard. The only difference is that senderId uses the camper method. All the names in Syncano are lowercase letters, so we tell Syncano that the attribute names are slightly different (in this way, our attribute names can be kept in iOS naming rules ).

Add an extension to ViewController. swift:

//MARK - Syncano
extension ViewController {

    func sendMessageToSyncano(message: JSQMessage) {
        let messageToSend = Message()
        messageToSend.text = message.text
        messageToSend.senderId = self.senderId
        messageToSend.channel = syncanoChannelName
        messageToSend.other_permissions = .Full
        messageToSend.saveWithCompletionBlock { error in
            if (error != nil) {
                //Super cool error handling
            }
        }
    }

    func downloadNewestMessagesFromSyncano() {
        Message.please().giveMeDataObjectsWithCompletion { objects, error in
            if let messages = objects as? [Message]! {
                self.messages = self.jsqMessagesFromSyncanoMessages(messages)
                self.finishReceivingMessage()
            }
        }
    }

    func jsqMessageFromSyncanoMessage(message: Message) -> JSQMessage {
        let jsqMessage = JSQMessage(senderId: message.senderId, senderDisplayName: message.senderId, date: message.created_at, text: message.text)
        return jsqMessage
    }

    func jsqMessagesFromSyncanoMessages(messages: [Message]) -> [JSQMessage] {
        var jsqMessages : [JSQMessage] = []
        for message in messages {
            jsqMessages.append(self.jsqMessageFromSyncanoMessage(message))
        }
        return jsqMessages
    }
}

These methods are used to communicate with Syncano.

SendMessageToSyncano (message: JSQMessage) converts a JSQMessage object to a Syncano object and submits it to Syncano. Note: After setting the senderId and text fields, you also need to set the chanel field-channel for real-time synchronization, And the other_permissions field-to specify who has the permission to access this object-this field is set to Full, indicating all users. DownloadNewestMessagesFromSyncano () is used to download the latest message and replace the original messages array with the server message. The jsqMessageFromSyncanoMessage (message: Message) and jsqMessagesFromSyncanoMessages (messages: [Message]) methods are used for conversion between the Message class and the JSQMessage class.

Next, modify the code so that the messages entered by the user can be sent to Syncano. Call the sendMessageToSyncano method in the didPressSendButton method:

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.sendMessageToSyncano(message)
        self.finishSendingMessage()
    }

Then, replace the Test message with a real Syncano message. In the viewDidLoad method, we will download the latest message. Note: we have deleted the previously added Test message:

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

Run the program and you will see a blank window. That's because there are no chat messages on the server. Send several messages and then restart the App. You will see that the message has been saved to the server. You can log on to your Syncano Dashboard to check whether all these messages are saved to the Message class.

Real-time!

This App also has a real-time function that is not implemented, that is, the client can immediately receive a message whenever the server receives it.

We can refresh the message list every few seconds in the background, but a better way is to use the Syncano channel.

In the setup () method, obtain the chat message from the channel:

func setup() {
        self.senderId = UIDevice.currentDevice().identifierForVendor?.UUIDString
        self.senderDisplayName = UIDevice.currentDevice().identifierForVendor?.UUIDString
        self.channel.delegate = self
        self.channel.subscribeToChannel()
    }

We set the channel delegate to self, so we need to implement the SCChannelDelegate protocol for self. Add an extension in ViewController. swift:

//MARK - Channels
extension ViewController : SCChannelDelegate {

    func addMessageFromNotification(notification: SCChannelNotificationMessage) {
        let message = Message(fromDictionary: notification.payload)
        if message.senderId == self.senderId {
            //we don't need to add messages from ourselves
            return
        }
        self.messages.append(self.jsqMessageFromSyncanoMessage(message))
        self.finishReceivingMessage()
    }

    func updateMessageFromNotification(notification: SCChannelNotificationMessage) {

    }

    func deleteMessageFromNotification(notification: SCChannelNotificationMessage) {

    }

    func chanellDidReceivedNotificationMessage(notificationMessage: SCChannelNotificationMessage!) {
        switch(notificationMessage.action) {
        case .Create:
            self.addMessageFromNotification(notificationMessage)
        case .Delete:
            self.deleteMessageFromNotification(notificationMessage)
        case .Update:
            self.updateMessageFromNotification(notificationMessage)
        default:
            break
        }
    }
}
Summary

So far, our App is still a semi-finished product. Now, you can share it with your friends, or continue with the third part.

This part of the code is downloaded here.

In the third part, we will learn how to enable user registration, verification, and UI modification, and how to display messages sent by different users differently. Stay tuned!

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.