Publish/Subscribe messaging app

The Ably Realtime service organizes the message traffic within applications into named channels. Channels are the “unit” of message distribution; clients attach to any number of channels to subscribe to messages, and every message published to a channel is broadcasted to all subscribers. This scalable and resilient messaging pattern is commonly called pub/sub.

As you can publish a message to any channel, channels provide a means for you to filter data by topic or enforce access control for your subscribers. Only subscribers for those channels will receive those messages.

Messages published can contain string, JSON object, JSON array or binary data payloads.

Publishing and subscribing for messages on channels with our channel API is trivial. Let’s get started.

Step 1 – Create your Ably app and API key

To follow this tutorial, you will need an Ably account. Sign up for a free account if you don’t already have one.

Access to the Ably global messaging platform requires an API key for authentication. API keys exist within the context of an Ably application and each application can have multiple API keys so that you can assign different capabilities and manage access to channels and queues.

You can either create a new application for this tutorial, or use an existing one.

To create a new application and generate an API key:

  1. Log in to your Ably account dashboard
  2. Click the “Create New App” button
  3. Give it a name and click “Create app”
  4. Copy your private API key and store it somewhere. You will need it for this tutorial.

To use an existing application and API key:

  1. Select an application from “Your apps” in the dashboard
  2. In the API keys tab, choose an API key to use for this tutorial. The default “Root” API key has full access to capabilities and channels.
  3. Copy the Root API key and store it somewhere. You will need it for this tutorial.

    Copy API Key screenshot

Step 2 – Setup an Xcode project and install Ably

We will start by creating an Xcode project for this tutorial. To build your own Xcode Project in Swift visit Apple developer website and get familiar with steps necessary to setup your own application.
When you setup your application delete the default ViewController.swift add new File → New → File… and choose Cocoa Touch Class.

Create new Cocoa Touch Class

Name your new class “ExampleViewController” and choose Swift as language:

Name new Cocoa Touch Class

After that navigate to Main.storyboard in your project, click on the ViewController that has already been added by default during project creation and from the Utilities that are located on the right choose Identity Inspector. Find the field labeled “Class” and select “ExampleViewController”.

Interface design

See this step in Github

To start using Ably you first need to install the Ably pod via CocoaPods. You need to add a Podfile to your project directory:

Shell scripttouch Podfile

Then add this line to your application’s Podfile:

Plain Textpod 'Ably'

Install it with:

Shell scriptpod install

To learn more about using CocoaPods in your project visit official CocoaPods guide.

Then in your files in which you will be using Ably import:

Swiftimport Ably

To connect to Ably, you need to instantiate the client library with the API key you copied in Step 1. API keys used with basic authentication for your own servers is generally preferred, however clients running on insecure devices should always use the token authentication scheme instead. In this example, we use an API key for simplicity.

Add the following to the file in which you imported the Ably library:

Swiftlet API_KEY = "INSERT-YOUR-API-KEY-HERE"
let client = ARTRealtime(key: API_KEY)

See this step in Github

Step 3 – Subscribe to messages

Now that the library is installed, you can subscribe to messages published on channels. Every app can have an arbitrary number of channels that should be used to filter the messages received by subscribing clients. For example, if building a news feed, you may want one channel for politics named “politics”, and another for sport named “sport”. A user interested in “sport” can subscribe to the “sport” channel to receive updates. If that user is not subscribed to the “politics” channel, then “politics” updates will not be delivered to that user.

If you have not previously had experience building a basic user interface in Xcode, please refer to Apple developer guide on how to build a simple UI and also learn more about adding IBOutlets and IBActions.
To be able to subscribe to a channel and send some initial messages, we will add a listener for new messages and add a button that publishes a message. Go to your ExampleViewController and add a UIButton from Object library. Name the action “subscribeAction”.

Binding UI objects

In a similar fashion add two UILabels and connect one of them so that it will show the last message received. Name it “receivedMessageText”.
Your ExampleViewController should look similar to this view:

Binding UI objects

Add this code to previously added IBAction:

Swiftlet channel = client.channels.get("sport")
self.receivedMessageText.text = ""

channel.subscribe { message in
    self.receivedMessageText.text = "\(message.timestamp) \(message.data)"
  }
}

See this step in Github

Step 4 – Publish a message

Publishing a message on a channel ensures that any number of subscribers on that channel receive the message in real time. To publish a message on the “sport” channel, call the publish method on the channel, specify an optional message event name as the first argument, and provide the payload as the second argument.

In this step add another UIButton and bind it to action named “publishAction”. Also, add one more UILabel and an UITextField – bind it in your code as “messageText” . Thanks to that users will be able to write their own messages.
Your view should now look like this:

Binding UI objects

You can also check if an error occurred while sending the message.
Add this code to previously added IBAction:

Swiftchannel.publish("update", data: messageText.text) { error in
  guard error == nil else {
    return self.showAlert("Error", message:
                          "There was an error while sending the message. \(error)")
  }
}

See this step in Github

You have now learned how to instantiate the Ably client, subscribe to a channel, and publish messages on that channel.

Download tutorial source code

The complete source code for each step of this tutorial is available on Github

We recommend that you clone the repo locally:

Shell scriptgit clone https://github.com/ably/tutorials.git

Checkout the tutorial branch:

Shell scriptgit checkout publish-subscribe-swift

In the project directory simply run:

Shell scriptpod install

Open example.xcworkspace and build the demo on your preferred iPhone simulator or device. Don’t forget to replace your ExampleViewController#API_KEY field by adding your Ably API key to ExampleViewController.swift.

Next steps

1. If you would like to find out more about how channels, publishing and subscribing works, see the Realtime channels and messages documentation
2. Learn more about Ably features by stepping through our other Ably tutorials
3. Gain a good technical overview of how the Ably realtime platform works
4. Get in touch if you need help