Getting started: Pub/Sub in Swift

This guide will get you started with Ably Pub/Sub in Swift.

It will take you through the following steps:

  • Create a client and establish a realtime connection to Ably.
  • Attach to a channel and subscribe to its messages.
  • Publish a message to the channel for your client to receive.
  • Join and subscribe to the presence set of the channel.
  • Retrieve the messages you sent in the guide from history.
  • Close a connection to Ably when it is no longer needed.

  • Sign up for an Ably account.
    • Create a new app, and create your first API key.
    • Your API key will need the publish, subscribe, presence and history capabilities.
  • Install the Ably CLI:
npm install -g @ably/cli
Copied!
  • Run the following to log in to your Ably account and set the default app and API key:
ably login ably apps switch ably auth keys switch
Copied!

To follow this guide in Xcode, use a new iOS project with the SwiftUI App template. All code can be added directly to your ContentView.swift file, inside the ContentView struct. Use the .onAppear modifier to run the Ably code when the view appears. No additional files or setup are needed. All print output will appear in Xcode’s debug console (View > Debug Area > Activate Console, or press Cmd+Shift+C).

  • Install the Ably SDK in your Swift project using Swift Package Manager:
Swift v1.2
dependencies: [ .package(url: "https://github.com/ably/ably-cocoa", from: "1.2.20") ]
Copied!

Clients establish a connection with Ably when they instantiate an SDK. This enables them to send and receive messages in realtime across channels.

  • Open up the dev console of your first app before instantiating your client so that you can see what happens.
  • Add the Ably import to the top of your ContentView file:
Swift v1.2
import Ably
Copied!
  • Create an instance of ARTRealtime with your API key and provide a clientId. This is the main entry point for the realtime library. The ARTRealtime client connects to Ably as soon as it’s instantiated, using a basic transport such as a raw TCP socket or a WebSocket:
Swift v1.2
let clientOptions = ARTClientOptions(key: "<loading API key, please wait>") clientOptions.clientId = "my-first-client" let realtime = ARTRealtime(options: clientOptions) realtime.connection.on { stateChange in print("Connection state changed to: \(stateChange.current)") if stateChange.current == .connected { print("Made my first connection!") } }
Demo Only
Copied!

You can monitor the lifecycle of clients’ connections, but for now just log a message to the console to know that the connection attempt was successful. You’ll see the message printed to your console, and you can also inspect the connection event in the dev console of your app.

To run:

  • Build and run the app in Xcode (Cmd+R).
  • Watch the Xcode debug console for connection state changes and messages.

Messages contain the data that a client is communicating, such as a short ‘hello’ from a colleague, or a financial update being broadcast to subscribers from a server. Ably uses channels to separate messages into different topics, so that clients only ever receive messages on the channels they are subscribed to.

  • Add the following lines to your .onAppear{} function to create a channel instance and register a listener to subscribe to the channel. Then run the app again:
Swift v1.2
let channel = realtime?.channels.get("my-first-channel") channel?.subscribe { message in print("Received message: \(message.data ?? "no data")") }
Copied!
  • Use the Ably CLI to publish a message to your channel. The message will be received by the client you’ve subscribed to the channel, and be logged to the console:
ably channels publish my-first-channel 'Hello!'
Copied!
  • In a new terminal tab, subscribe to the same channel using the CLI:
ably channels subscribe my-first-channel
Copied!
  • Now you can publish a message from your Swift code to the channel:
Swift v1.2
channel?.publish("greeting", data: "Hello from Swift!") { error in guard error == nil else { print("Error publishing message: \(error!.message)") return } print("Message successfully published") }
Copied!

When you publish this message, it will be received by both your Swift client and the CLI subscription.

To run:

  • Build and run the app again.
  • Use the Ably CLI as described to publish/subscribe and see output in the Xcode debug console.

Presence enables clients to be aware of one another if they are present on the same channel. You can then show clients who else is online, provide a custom status update for each, and notify the channel when someone goes offline.

  • Add the following code to subscribe to presence events, which lets you know when clients enter, update, and leave the presence set for this channel:
Swift v1.2
channel?.presence.subscribe { presenceMessage in print("Presence event: \(presenceMessage.action) - Client: \(presenceMessage.clientId ?? "no client id") - \(presenceMessage.data ?? "no data")") } channel?.presence.enter("I'm here!") { error in guard error == nil else { print("Error entering presence set: \(error!.message)") return } print("Successfully entered presence set") }
Copied!
  • In the dev console of your first app, attach to my-first-channel. Enter a clientId, such as my-dev-console, and then join the presence set of the channel. You’ll see that my-first-client is already present in the channel.
  • You can have another client join the presence set using the Ably CLI:
ably channels presence enter my-first-channel --client-id "my-cli" --profile-data '{"status":"learning about Ably!"}'
Copied!

To run:

  • Build and run the app.
  • Use the Ably CLI or dev console to join presence and see events in the Xcode debug console.

You can retrieve previously sent messages using the history feature. Ably stores all messages for 2 minutes by default in the event a client experiences network connectivity issues. This can be extended for longer if required.

If more than 2 minutes has passed since you published a regular message (excluding the presence events), then you can publish some more before trying out history. You can use the Ably CLI to do this.

For example, using the Ably CLI to publish 5 messages:

ably channels publish --count 5 my-first-channel "Message number {{.Count}}"
Copied!
  • Add the following code to retrieve any messages that were recently published to the channel:
Swift v1.2
let query = ARTRealtimeHistoryQuery() query.limit = 25 // Maximum number of messages to retrieve try channel?.history(query) { paginatedResult, error in guard error == nil else { print("Error retrieving message history: \(error!.message)") return } guard let paginatedResult = paginatedResult else { print("No results received") return } print("Retrieved \(paginatedResult.items.count) messages from history") for message in paginatedResult.items { print("Message: \(message.data ?? "no data")") } }
Copied!

The output will look similar to the following:

[ "Message number 5", "Message number 4", "Message number 3", "Message number 2", "Message number 1" ]
Copied!

To run:

  • Build and run the app.
  • Use the Ably CLI to publish messages if needed, then check the Xcode debug console for history output.

Connections are automatically closed approximately 2 minutes after no heartbeat is detected by Ably. Explicitly closing connections when they are no longer needed is good practice to help save costs. It will also remove all listeners that were registered by the client.

Note that messages are streamed to clients as soon as they attach to a channel, as long as they have the necessary capabilities. Clients are implicitly attached to a channel when they call subscribe(). Detaching from a channel using the detach() method will stop the client from being streamed messages by Ably.

Listeners registered when subscribing to a channel are registered client-side. Unsubscribing by calling unsubscribe() will remove previously registered listeners for that channel. Detaching from a channel has no impact on listeners. As such, if a client reattaches to a channel that they previously registered listeners for, then those listeners will continue to function upon reattachment.

  • Close the connection using the close method:
Swift v1.2
// Simulate a delay before closing the connection DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) { realtime.close() print("Connection closed") }
Copied!

To run:

  • Build and run the app.
  • After 10 seconds, the connection will close and a message will appear in the Xcode debug console.

Continue to explore the documentation with Swift as the selected language:

Read more about the concepts covered in this guide:

You can also explore the Ably CLI further, or visit the Pub/Sub API references.

Select...