Quick Start: iOS (Swift 2)

  • Jul 5, 2016
  • Starting Guide
  • iOS
  • Swift 2

Get your free API key

Before you can use the Realtime Messaging API you need to register, create a "Realtime Messaging Subscription" and make a note of your Realtime application key (this document will refer to it as APP_KEY).

A note about security

This Quick Start Guide assumes your APP_KEY has authentication disabled (by default and for simplity reasons all Realtime application keys have authentication disabled when they are created).

This means you can use any token to connect to a Realtime server. In the examples below we'll use testToken.

When you're ready for production you should enable authentication (we'll cover this on the Security section ahead).

Swift 3 or Objective-C?

This guide uses the Swift 2 language. If you are an Objective-C developer please check the Objective-C guide.

If you're already using Swift 3 please check the Swift 3 guide.

Install the client library

The best way to install the Realtime library is using CocoaPods, a library dependency manager for Xcode projects. If you don't have it already installed please follow these setup instructions before proceeding.

Open a terminal window in your project directory and create an empty Podfile by running the following command:

pod init
        

Open your Podfile (created in your project directory) and enter the Realtime Messaging Pod configuration:

pod 'RealtimeMessaging-iOS-Swift', '~> 2.1'
        

The Podfile should look like this (for a Swift project named iosExample):

# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

target 'iosExample' do
  # Comment this line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for iosExample

  pod 'RealtimeMessaging-iOS-Swift', '~> 2.1'

  target 'iosExampleTests' do
    inherit! :search_paths
    # Pods for testing
  end

  target 'iosExampleUITests' do
    inherit! :search_paths
    # Pods for testing
  end

end
        

Now that you have your Podfile configured run the following command to install the required dependencies:

pod install     		
     	

Close your Xcode project and open the xcworkspace that was created (a file named {your app name}.xcworkspace in your project directory). This should be the file you use everyday to create your app from now on.

Open a connection to Realtime

Before you can start sending and receiving messages you need to open a connection to a Realtime server. To perform this action the class where you'll be using the Realtime client needs to import the Realtime Messaging module and implement the interface OrtcClientDelegate. In a single view app it could be the Xcode generated ViewController class (in your app you'll probably want to create a new class, but that's up to you).

The ViewController class definition would look like this:

import RealtimeMessaging_iOS_Swift

class ViewController: UIViewController, OrtcClientDelegate {
	...
}
        

Sometimes Xcode shows an error saying that "Cannot load underlying module for 'RealtimeMessaging_iOS_Swift'" but don't worry, it'll go away when you build your app for the first time.

You'll also need to implement the OrtcClientDelegate interface so add the following methods to your ViewController class (you can keep them empty for now):

func onConnected(ortc: OrtcClient){
	// will be invoked when the connection is established      
}

func onDisconnected(ortc: OrtcClient){
	// will be invoked when the connection is disconnected   
}

func onSubscribed(ortc: OrtcClient, channel: String){
    // will be invoked when a channel is subscribed
}

func onUnsubscribed(ortc: OrtcClient, channel: String){
	// will be invoked when a channel is unsubscribed 
}

func onException(ortc: OrtcClient, error: NSError){
	// will be invoked when an exception is raised   
}

func onReconnecting(ortc: OrtcClient){
	// will be invoked when a reconnection procedure has started   
}

func onReconnected(ortc: OrtcClient){
    // will be invoked when a reconnection procedure has ended
    // and we have a new established connection  
}

        

Now let's establish a Realtime connection. Enter the following code in your viewDidLoad method replacing APP_KEY with your Realtime application key:

var ortc: OrtcClient?
ortc = OrtcClient.ortcClientWithConfig(self)
ortc!.clusterUrl = "https://ortc-developers.realtime.co/server/ssl/2.1/"
ortc!.connect("APP_KEY", authenticationToken: "testToken")
        

Subscribe to a channel

Realtime Messaging is a pub/sub system based on channels (aka as topics). This means that each connected client can only receive messages on channels that were subscribed. To subscribe a channel you simply define the channel name and which callback function should handle each message received.

However you must guarantee that your client is propertly connected before you subscribe a channel by implementing the onConnected event delegate handler. This event will be invoked when the connection is ready for subscriptions and/or sending messages.

The following code shows how to subscribe to channel myChannel using the onConnected event.

func onConnected(ortc: OrtcClient){
    // will be invoked when the connection is established
    
    ortc.subscribe("myChannel", subscribeOnReconnected: true,
            onMessage: {
                (ortcClient:OrtcClient!, channel:String!, msg:String!) -> Void in
                    NSLog("Received message: %@ on channel: %@", msg!, channel!)
            }
    )
}
		

You're now ready to build and run your app! The previous code will show each message received through myChannel in your Xcode Debug Area.

To send messages to test your app you can use the simple console available in the Realtime Account Management website or the advanced console available at console.realtime.co

Send a message to a channel

As soon as you are connected you can start sending messages directly from your iOS app using the send method. Add the following code to your onConnected event handler.

ortc.send("myChannel", message: "A simple string message")			
		

Note that Realtime messages are text-based (UTF-8 encoded).

To receive messages sent from your app you can use the simple console available in the Realtime Account Management website or the advanced console available at console.realtime.co. Don't forget to subscribe the channel myChannel

More iOS resources

The Realtime iOS Swift SDK has more features that are beyond the scope of this quick starting guide. Please refer to the Swift Group Chat example in GitHub to test the other SDK features (including push notifications).

Back to Android Quick Start - Next: Security

If you find this interesting please share: