PubNub Logo Docs
Support Contact Sales Login Try Our APIs

›IOS

Collapse all
Dark mode

Back to Home

Overview

  • In-App Chat

Chat Components

  • Overview
  • REACT

    • React Components

    ANDROID

    • Getting Started
    • UI Components
    • Data Components
    • Chat Provider

    IOS

    • Getting Started
    • UI Components
    • Data Components
    • Chat Provider

SDKs

  • Overview
  • USERS

    • Setup
    • Metadata
    • Permissions
    • Presence
    • Mentions

    CHANNELS

    • Types and Names
    • Metadata
    • Subscriptions
    • Memberships

    MESSAGES

    • Sending Messages
    • Message Storage
    • Unread Counts
    • File Upload
    • Typing Indicators
    • Read Receipts
    • Emoji Reactions
    • Update Messages
    • Delete Messages
    • Message Webhooks

    PUSH NOTIFICATIONS

    • Overview

    MODERATION

    • Profanity Filters
    • Flag Messages
    • Ban Users
    • Mute Users
    • Spam Prevention

    INTEGRATIONS

    • Overview
    • Content Moderation
    • Image Moderation
    • Language Translation
    • Chatbots
    • GIFs
    • Stickers

Moderation Dashboard

  • Overview
  • Getting Started
  • FEATURES

    • Automatic Text Moderation
    • Automatic Image Moderation
    • Manual Message Moderation
    • Manual User Moderation
    • User Management
    • Channel Management
  • Required Configuration

Debug Console
Network Status

Getting started

See how you can get a 1:1 chat app quickly up and running.

You will download a sample iOS app that uses two PubNub Chat Components for iOS: MessageInput and MessageList. Then, you'll run the app and send your first message by typing it in the message input field. The messages will pile up on the screen as you send them.

Prerequisites

  • Xcode (>= Xcode 13)
  • git
Tools used

This guide uses PubNub Swift SDK (>= 4.1.2) for chat components and UIKit as the UI Toolkit.

Steps

Follow the steps to get your PubNub keys, clone the sample iOS project files with chat components, and run the app to send your first message.

Create a PubNub account

Before you start, you need to obtain Publish and Subscribe Keys for your chat app. You need them to initialize the PubNub object in your app to send and receive messages through the PubNub Network. To get both keys, sign in or create an account on the Admin Portal. The autogenerated Demo Keyset in My First App already contains the configuration required to complete this guide.

Clone a sample chat app with components

Clone the chat-components-ios-examples repository.

git clone git@github.com:pubnub/chat-components-ios-examples.git

If you're authenticated into Xcode with your GitHub account, you can also open the project directly from GitHub using the Open in Xcode button.

Configure PubNub keys

  1. Once you've cloned the repository, open the getting-started project in Xcode.

  2. Inside SceneDelegate, replace both PUBNUB_PUBLISH_KEY and PUBNUB_SUBSCRIBE_KEY with your Publish and Subscribe Keys from your PubNub account in the Admin Portal:

    let PUBNUB_PUBLISH_KEY = "myPublishKey"
    let PUBNUB_SUBSCRIBE_KEY = "mySubscribeKey"
    

The rest of the configuration is already provided:

  • To associate a sender/current user with the PubNub messages, it's required to configure the uuid parameter that stands for Universally Unique Identifier and refers to your user ID in the database. The app already sets uuid in SceneDelegate using the pubnubConfiguration property. Both publishKey and subscribeKey parameters will use PUBNUB_PUBLISH_KEY and PUBNUB_SUBSCRIBE_KEY defined in the previous step.

    lazy var pubnubConfiguration = {
      return PubNubConfiguration(
        publishKey: PUBNUB_PUBLISH_KEY,
        subscribeKey: PUBNUB_SUBSCRIBE_KEY,
        uuid: "myFirstUser"
      )
    }()
    
    UUID

    For simplicity, the getting started app sets a static UUID. However, if you implement chat in your app, you should generate a UUID per user, device, and server and reuse it for their lifetime. Using separate UUIDs in real-life apps is particularly important as it impacts your overall billing and the way your app works.

  • The app calls ChatProvider which initializes all the data components. These components are responsible for providing data to UI, setting the default theme, and communicating with the PubNub service. ChatProvider is used to facilitate the majority of the functionality provided by PubNub Chat Components for iOS.

    let provider = PubNubChatProvider(
      pubnubProvider: PubNub(configuration: pubnubConfiguration)
    )
    

    Inside the scene(_:willConnectTo:options:) method of SceneDelegate, ChatProvider is initialized by passing in PubNubConfiguration. To learn more about this SceneDelegate method, see Apple's official documentation.

  • As part of initialization, ChatProvider configures the default CoreData instance. In SceneDelegate, you can use the preloadData(_:) method to include any predefined data that should be added before using the chat components.

    func preloadData(_ chatProvider: PubNubChatProvider) {
      // Creates a user object with uuid
      let user = PubNubChatUser(
        id: chatProvider.pubnubConfig.uuid,
        name: "myFirstUser",
        avatarURL: URL(string: "https://picsum.photos/seed/\(chatProvider.pubnubConfig.uuid)/200")
      )
    
      // Creates a channel object
      let channel = PubNubChatChannel(
        id: defaultChannelId,
        name: "Default",
        type: "direct",
        avatarURL: URL(string: "https://picsum.photos/seed/\(defaultChannelId)/200")
      )
    
      // Creates a membership between the user and the channel for subscription purposes
      let membership = PubNubChatMember(channel: channel, member: user)
    
      // Subscribes to the default channel
      chatProvider.pubnubProvider.subscribe(.init(channels: [defaultChannelId], withPresence: true))
    
      // Fills the database with the user, channel, and memberships data
      chatProvider.dataProvider.load(members: [membership])
    }
    

    ChatProvider can be stored at anytime using the corresponding load() methods for each of the object data types:

    • load(channels:)
    • load(users:)
    • load(members:)
    • load(messages:)
  • The scene(_:willConnectTo:options:) method inside SceneDelegate finishes by loading the MessageList component as the default (root) View Controller.

    // Creates the default ChannelList and MemberList components view models
    guard let channelListViewModel = chatProvider?.senderMembershipsChanneListComponentViewModel(),
          let messageListViewModel = try? chatProvider?.messageListComponentViewModel(pubnubChannelId: defaultChannelId) else {
      preconditionFailure("Could not create intial view")
    }
    
    // Creates the navigation structure
    let navigation = UINavigationController()
    
    // Loads the MessageList as the root view, but allows for the ChannelList to be the previous view
    navigation.viewControllers = [
      channelListViewModel.configuredComponentView(),
      messageListViewModel.configuredComponentView()
    ]
    
    // Sets the component as the root view controller
    window.rootViewController = navigation
    self.window = window
    window.makeKeyAndVisible()
    

    To make the application easier to use, the ChannelList component is also loaded as the previous View Controller in the app's navigation hierarchy. This is visualized by the Back button inside the navigation bar of the MessageList component that you will see once the app is up and running.

Run the chat app

Choose a simulator and run the getting-started app.

Send your first message

When your application opens up, type and send your first message. The messages will pile up on the screen as you send them.

Getting Started app for iOS

To verify that the app is connected to the PubNub Network, mock a real-live chat conversation with myFirstUser. Open the app in a new simulator, send a message from one simulator and reply to it from another.

←Chat ProviderUI Components→
  • Prerequisites
  • Steps
    • Create a PubNub account
    • Clone a sample chat app with components
    • Configure PubNub keys
    • Run the chat app
    • Send your first message
© PubNub Inc. - Privacy Policy