Skip to main content

Getting Started with Momento Topics in Swift

If you need to get going quickly with Swift and Momento Topics, this page contains the basic API calls you'll need. Check the Swift SDK examples for complete, working code samples.

Install the Momento SDK

The latest version of the Momento Swift SDK is available on GitHub: momentohq/client-sdk-swift.

Get your Momento API key

You'll need a Momento API key. You can get one from the Momento Web Console. Once you have your token, store it in an environment variable so that the Momento client can consume it:

export MOMENTO_API_KEY=<your api key here>

Note: it is best practice to put the API key into something like AWS Secret Manager or GCP Secret Manager instead of an environment variable for enhanced security, but we are using one here for demo purposes.

Set up a TopicClient

This code creates the TopicClient that you will use to interact with your pub/sub topic.

do {
let credentialProvider = try CredentialProvider.fromEnvironmentVariable(envVariableName: "MOMENTO_API_KEY")
let topicClient = TopicClient(
configuration: TopicClientConfigurations.iOS.latest(),
credentialProvider: credentialProvider
)
} catch {
print("Unable to create topic client: \(error)")
exit(1)
}

Publish a message to a topic

This is an example of publishing a message to a topic called "topic", then catching the return value to check if the publish was successful.

let result = await topicClient.publish(
cacheName: cacheName,
topicName: "topic",
value: "value"
)
switch result {
case .success(_):
print("Successfully published message!")
case .error(let err):
print("Unable to publish message: \(err)")
exit(1)
}

Subscribe to a topic

This is an example of subscribing to a topic called "topic". When messages are published to this topic, the code here receives and prints them asynchronously.

let subscribeResponse = await topicClient.subscribe(cacheName: cacheName, topicName: "topic")

#if swift(>=5.9)
let subscription = switch subscribeResponse {
case .error(let err): fatalError("Error subscribing to topic: \(err)")
case .subscription(let sub): sub
}
#else
let subscription: TopicSubscription
switch subscribeResponse {
case .error(let err):
fatalError("Error subscribing to topic: \(err)")
case .subscription(let sub):
subscription = sub
}
#endif

// unsubscribe in 5 seconds
Task {
try await Task.sleep(nanoseconds: 5_000_000_000)
subscription.unsubscribe()
}

// loop over messages as they are received
for try await item in subscription.stream {
var value: String = ""
switch item {
case .itemText(let textItem):
value = textItem.value
print("Subscriber recieved text message: \(value)")
case .itemBinary(let binaryItem):
value = String(decoding: binaryItem.value, as: UTF8.self)
print("Subscriber recieved binary message: \(value)")
case .error(let err):
print("Subscriber received error: \(err)")
}
}

Running the code

You can find complete, working examples in the Swift SDK GitHub repo examples directory.

info

Beyond these basic API calls check out the API reference page for more information on the full assortment of Momento API calls.