---
source_url: https://www.pubnub.com/docs/sdks/swift
title: Swift API & SDK Docs 10.1.6
updated_at: 2026-05-20T11:08:21.312Z
sdk_name: PubNub Swift SDK
sdk_version: 10.1.6
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Swift API & SDK Docs 10.1.6

PubNub Swift SDK, use the latest version: 10.1.6

Install:

```bash
Add PubNub via Swift Package Manager or CocoaPods@10.1.6
```

This guide walks you through a simple "Hello, World" application that demonstrates the core concepts of PubNub:

* Setting up a connection
* Sending messages
* Receiving messages in real-time

## Overview

This guide will help you get up and running with PubNub in your Swift application. Since Swift is commonly used across different platforms, we provide two implementation paths:

* **SwiftUI**: For developers building iOS apps using SwiftUI
* **UIKit**: For developers building iOS apps using UIKit

The core PubNub concepts and API usage remain the same across both paths, but implementation details like lifecycle management and UI updates differ. Select the appropriate tab in each section to see platform-specific guidance.

While this guide focuses on Swift for Apple platforms, the PubNub Swift SDK is also compatible with Linux environments.

## Prerequisites

Before we dive in, make sure you have:

* A basic understanding of Swift
* Xcode 14.0 or later
* A PubNub account (we'll help you set this up!)

## Setup

### Get your PubNub keys

First, get your PubNub keys:

* [Sign in](https://admin.pubnub.com/#/login) or [create an account](https://admin.pubnub.com/#/signup) on the PubNub Admin Portal.
* Create an app (or use an existing one).
* Find your publish and subscribe keys in the app dashboard.

When you create a new app, PubNub automatically generates your first set of keys. While you can use the same keys for development and production, we recommend creating separate keysets for each environment for better security and management.

### Install the SDK

:::note SDK version
Always use the latest SDK version to have access to the newest features and avoid security vulnerabilities, bugs, and performance issues.
:::

Choose one of these methods to add the Swift SDK to your iOS app:

#### Swift Package Manager

1. In Xcode, select **File** > **Add Package Dependencies...**.
2. Enter the package URL: `https://github.com/pubnub/swift.git`.
3. Select **Up to Next Major Version** with "10.1.6" as the minimum version.
4. Click **Add Package**.
5. From the list of package products, assign `PubNubSDK` to your target application.

#### CocoaPods

1. Install CocoaPods if you haven't already: gem install cocoapods
2. Add PubNub to your Podfile: pod 'PubNubSwift', '~> 10.1.6'
3. Run pod install in your project directory
4. Open the generated .xcworkspace file

#### Carthage

1. Add PubNub to your Cartfile: github "pubnub/swift" ~> 10.1.6
2. Run carthage update --use-xcframeworks.
3. Drag the built PubNub.xcframework into your Xcode project's Frameworks, Libraries, and Embedded Content section.

You can integrate the PubNub Swift SDK into any Swift application:

#### Swift Package Manager

Add PubNub as a dependency to your `Package.swift` file:

```swift
dependencies: [
  .package(url: "https://github.com/pubnub/swift.git", from: "10.1.6")
]
```

#### Source code

1. Clone the GitHub repository: git clone https://github.com/pubnub/swift.git
2. Include the Swift package in your project as a dependency.

## Steps

### Initialize PubNub

In your Swift application, you'll need to initialize the PubNub client with your unique keys to establish a connection to the PubNub network. This is the minimum configuration required to send and receive messages with PubNub in your application.

Make sure to replace the demo keys with your app's publish and subscribe keys from the Admin Portal.

#### SwiftUI

1. Create a view model class and keep a strong reference to your PubNub instance: 1import SwiftUI2import PubNubSDK3 4class PubNubViewModel: ObservableObject {5 // Reference to the SDK instance6 private let pubnub: PubNub7 8 init() {9 // PubNub instance configured with publish/subscribe keys and unique user ID10 pubnub = PubNub(configuration: PubNubConfiguration(11 publishKey: "demo",12 subscribeKey: "demo",13 userId: "device-\(UUID().uuidString.prefix(8))"14 )) 15 }16}
2. Initialize the view model in your App entry point: 1import SwiftUI2import PubNubSDK3 4@main5struct MyApp: App {6 var body: some Scene {7 WindowGroup {8 ContentView()9 .environmentObject(PubNubViewModel())10 }11 }12}
3. Access the view model in your view using @EnvironmentObject: 1import SwiftUI2import PubNubSDK3 4struct ContentView: View {5 @EnvironmentObject var pubNubViewModel: PubNubViewModel6 7 var body: some View {8 Text("Hello, PubNub!")9 }10}

#### UIKit

In your view controller, create a PubNub instance and store it as a strong reference:

```swift
import UIKit
import PubNubSDK

// A view controller that demonstrates basic PubNub functionality
class ViewController: UIViewController {
  // PubNub instance configured with publish/subscribe keys and unique user ID
  private let pubnub: PubNub = PubNub(configuration: PubNubConfiguration(
    publishKey: "demo",
    subscribeKey: "demo",
    userId: "device-\(UUID().uuidString.prefix(8))"
  ))
}
```

For more information, refer to the [Configuration](https://www.pubnub.com/docs/sdks/swift/api-reference/configuration) section of the SDK documentation.

### Set up event listeners

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event received. This is essential for building interactive real-time applications with PubNub.

#### SwiftUI

1. Add a @Published property to PubNubViewModel to store incoming messages: 1@Published var messages: [String] = []
2. In the same class, create a Subscription object for your channel and set up event listeners in the setupMessageHandling() method to handle PubNub events: 1import SwiftUI2import PubNubSDK3 4class PubNubViewModel: ObservableObject {5 // Holds the streamed messages6 @Published var messages: [String] = []7 // Reference to the SDK instance8 private let pubnub: PubNub9 10 // A dedicated subscription object for the example chat channel11 lazy var subscription: Subscription? = pubnub12 .channel("hello_world")13 .subscription(options: ReceivePresenceEvents())14 15 init() {16 pubnub = PubNub(configuration: PubNubConfiguration(17 publishKey: "demo",18 subscribeKey: "demo",19 userId: "device-\(UUID().uuidString.prefix(8))"20 ))21 22 setupConnectionHandling()23 setupMessageHandling()24 }25 26 private func setupConnectionHandling() {27 pubnub.onConnectionStateChange = { [weak self] newStatus in28 print("Connection status changed: \(newStatus)")29 30 // When connected, publish a welcome message31 if case .connected = newStatus {32 self?.sendWelcomeMessage()33 } else {34 // Handle other connection states according to your needs35 }36 }37 }38 39 private func setupMessageHandling() {40 subscription?.onMessage = { [weak self] message in41 print("Message received: \(message.payload.stringOptional ?? "N/A")")42 self?.messages.append(message.payload.stringOptional ?? "N/A")43 }44 }45 46 private func sendWelcomeMessage() {47 // This function will be defined in the next section48 }49}

#### UIKit

Create a `Subscription` object for your channel and set up event listeners in the `setupMessageHandling()` method to handle PubNub events:

```swift
import UIKit
import PubNubSDK

// A view controller that demonstrates basic PubNub chat functionality
class ViewController: UIViewController {
  // PubNub instance configured with publish/subscribe keys and unique user ID
  private let pubnub: PubNub = PubNub(configuration: PubNubConfiguration(
    publishKey: "demo",
    subscribeKey: "demo",
    userId: "device-\(UUID().uuidString.prefix(8))"
  ))

  // A dedicated subscription object for the example chat channel
  private lazy var subscription: Subscription? = pubnub
    .channel("hello_world")
    .subscription(queue: .main, options: ReceivePresenceEvents()
  )
  
  override func viewDidLoad() {
    super.viewDidLoad()
    setupConnectionHandling()
    setupMessageHandling()
  }
  
  private func setupConnectionHandling() {
    pubnub.onConnectionStateChange = { [weak self] newStatus in
      print("Connection status changed: \(newStatus)")

      // Connection status changes are posted on the main thread.
      // No manual synchronization needed
      self?.updateConnectionStatus(newStatus)

      // When connected, publish a welcome message
      if case .connected = newStatus {
        self?.sendWelcomeMessage()
      } else {
        // Handle other connection states according to your needs
      }
    }
  }

  private func setupMessageHandling() {
    subscription?.onMessage = { [weak self] message in
      print("Message received: \(message.payload.stringOptional ?? "")")
      self?.displayMessage(message)
    }
  }

  private func displayMessage(_ message: PubNubMessage) {
    // Update your UI to display the message
    // For example, add it to a UITableView or UILabel
  }

  private func updateConnectionStatus(_ status: ConnectionStatus) {
    // Update UI to reflect connection status
    // For example, change a status indicator color
  }

  private func sendWelcomeMessage() {
    // This function will be defined in the next section
  }
}
```

For more information, refer to the [Listeners](https://www.pubnub.com/docs/sdks/swift/api-reference/configuration#event-listeners) section of the SDK documentation.

### Trigger a subscription

To receive messages sent to a particular channel, you *subscribe* to it. When you subscribe to a channel, you'll receive all messages published to that channel in real-time.

It is best to define the subscription before you introduce the listeners and then send the `subscribe()` call, so place the relevant code in the appropriate places within your app.

#### SwiftUI

The following example demonstrates how to subscribe to a channel when a view appears and unsubscribe when it disappears:

```swift
import SwiftUI
import PubNubSDK

struct ContentView: View {
  @EnvironmentObject var pubNubViewModel: PubNubViewModel
  
  var body: some View {
    List(pubNubViewModel.messages, id: \.self) { message in
      Text(message)
    }
    .onAppear {
      pubNubViewModel.subscription?.subscribe()
    }
    .onDisappear {
      pubNubViewModel.subscription?.unsubscribe()
    }
  }
}
```

#### UIKit

The following example shows how to subscribe to a channel when the view appears and unsubscribe when it disappears by overriding `viewWillAppear(_:)` and `viewWillDisappear(_:)` in your view controller:

```swift
override func viewWillAppear(_ animated: Bool) {
  super.viewWillAppear(animated)
  // Subscribe to the channel
  subscription?.subscribe()
}
  
override func viewWillDisappear(_ animated: Bool) {
  super.viewWillDisappear(animated)    
  // Unsubscribe when view disappears
  subscription?.unsubscribe()
}
```

For more information, refer to the [Subscribe](https://www.pubnub.com/docs/sdks/swift/api-reference/publish-and-subscribe#subscribe) section of the SDK documentation.

### Publish messages

When you publish a message to a channel, PubNub delivers that message to everyone who subscribes to that channel. In this app, publishing a message is triggered when the status listener detects a successful connection to a channel.

A message can be any type of JavaScript Object Notation (JSON)-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB.

#### SwiftUI

Implement the `sendWelcomeMessage()` method defined earlier:

```swift
// Called when the connection is established
func sendWelcomeMessage() {
  pubnub.publish(
    channel: "hello_world",
    message: "Hello from iOS!"
  ) { result in
    switch result {
    case .success(let response):
      print("Message published successfully at \(response.timetokenDate)")
    case .failure(let error):
       print("Failed to publish message: \(error.localizedDescription)")
    }
  }
}
```

#### UIKit

Implement the `sendWelcomeMessage()` method defined earlier:

```swift
// Called when the connection is established
func sendWelcomeMessage() {
  pubnub.publish(
    channel: "hello_world",
    message: "Hello from iOS!"
  ) { result in
    switch result {
    case .success(let response):
      print("Message published successfully at \(response.timetokenDate)")
    case .failure(let error):
       print("Failed to publish message: \(error.localizedDescription)")
    }
  }
}
```

For more information, refer to the [Publish](https://www.pubnub.com/docs/sdks/swift/api-reference/publish-and-subscribe#publish) section of the SDK documentation.

### Run the app

Once you've implemented the initialization, event listeners, subscription, and publishing functionality, you're ready to run your application and test the real-time messaging capabilities.

Follow these steps:

1. Build and run your app in Xcode (⌘+R).
2. Wait for the connection to establish (check the console for status updates).
3. You should see the welcome message appear when the connection is successful.
4. Try sending messages using the UI you've created.

When you run the application, you should see output similar to the following:

```bash
Connection status changed: connected
Message published successfully at 2023-10-23 15:42:36 +0000
Message received: Hello from iOS!
```

## Complete example

Download the complete working example that puts everything together.

### SwiftUI

[Getting Started guide - SwiftUI](https://www.pubnub.com/assets/files/GettingStarted-SwiftUI-4f196125968319f1608bd23f5da28e8f.zip)

### UIKit

[Getting Started guide - UIKit](https://www.pubnub.com/assets/files/GettingStarted-UIKit-6183c005507ed2c3049122120f159a4a.zip)

### Troubleshooting

If you don't see the expected output, here are some common issues and how to fix them:

| Issue | Possible Solutions |
| --- | --- |
| No connection message | Check your internet connection., Verify your publish and subscribe keys are correct., Make sure you're not behind a firewall blocking PubNub's connections. |
| Message not received | Double-check that you're subscribed to the correct channel., Verify that the message was actually sent (check for any error messages)., Make sure you're waiting long enough for the message to be delivered. |
| Build errors | Ensure you've added the PubNub dependency correctly., Check that you're using a compatible version of Swift., Make sure all imports are correct. |

## Next steps

Great job! 🎉 You've successfully created your first PubNub application. Here are some exciting things you can explore next:

### Build chat

* Learn about the [Swift Chat SDK](https://www.pubnub.com/docs/chat/swift-chat-sdk) for ready-to-use chat features.
* Add typing indicators and read receipts.

### Advanced features

* Try out [Presence](https://www.pubnub.com/docs/sdks/swift/api-reference/presence) to track online/offline status.
* Implement [Message Persistence](https://www.pubnub.com/docs/sdks/swift/api-reference/storage-and-playback) to store and retrieve messages.
* Use [Access Manager](https://www.pubnub.com/docs/sdks/swift/api-reference/access-manager) to secure your channels.

### Real examples

* Explore our [GitHub repository](https://github.com/pubnub/swift/) for more code samples.

### More help

* Check out the [SDK reference documentation](https://www.pubnub.com/docs/sdks/swift/api-reference/configuration) for detailed API information.
* Visit the [support portal](https://support.pubnub.com/) for additional resources.
* Ask the AI assistant (the looking glass icon at the top of the page) for help.

## Terms in this document

* **Publish Key** - A unique identifier that allows your application to send messages to PubNub channels. It's part of your app's credentials and should be kept secure.
* **PubNub** - PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including: Message delivery and persistence, Presence detection, Access control, Push notifications, File sharing, Serverless processing with Functions and Events & Actions, Analytics and monitoring with BizOps Workspace, AI-powered insights with Illuminate.
* **Subscribe Key** - A unique identifier that allows your application to receive messages from PubNub channels. It's part of your app's credentials and should be kept secure.