Back to Blog

Connecting to Agora with Tokens — Using Swift

Connecting to Agora with Tokens — Using Swift

Introduction

When using the Agora platform, one good way to have a layer of security on your stream is to add a token service.

In this tutorial, you learn how to fetch an Agora token from a web service running an Agora token server.

To jump straight to a full iOS app that requests a token from a specified Agora token server, click to see this repository.

Prerequisites

Project Setup

A previous article on how to create a token server can be found here. This GitHub repository has all the code laid out to quickly launch a token server.

When you have your token server set up, you need to pull it into your application. This tutorial shows you how to achieve this in Swift.

Fetching the Token

You need to determine the full URL to reach your token service. In my example, the service is running on the local machine, which is why I’m looking at "http://localhost:8080/...". I’m also using my-channel as the channel name, and 0 as the userId.

If you want to host the server on your computer but fetch the token from an iOS device, you can use a service such as ngrok to route requests to localhost (see ngrok — secure introspectable tunnels to localhost).

guard let tokenServerURL = URL(
    string: "http://localhost:8080/rtc/my-channel/publisher/uid/0/"
) else {
    return
}

Next, we need to make a request. For this I’m using URLRequest from Foundation. Set the request’s httpMethod to GET, create the task using URLSession.shared.dataTask, and then start the task using task.resume(), as such:

var request = URLRequest(url: tokenServerURL, timeoutInterval: 10)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(
    with: request
) { data, response, err in
    // data task body here
}
task.resume()

Inside the data task body is where we can fetch the returned token. We can put something like this:

guard let data = data else {
    // No data, no token
    return
}
// parse response into json
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
// check that json has key "rtcToken"
let responseJSON = try? JSONSerialization.jsonObject(
    with: data, options: []
) as? [String: Any]
if let token = responseJSON?["rtcToken"] as? String {
    // Key "rtcToken" found in response, assigning to tokenToReturn
    print("the token is: (token)")
}

The main method might have already returned by the time the token reaches our device, so in the full example below I have added a DispatchSemaphore, which is used to hold on until we have the response. This way we can return the token straight from the method, but this will be blocking, so do not run this on the main thread if you don’t have to.

Staying Connected

All tokens provided through this method expire. The length of time until they expire can be set by the token server, or if altered, can be set as a parameter sent in the request.

When a connected user’s token will expire in 30 seconds, a callback from AgoraRtcEngineDelegate is called. This method is a good place from which to then contact the token server again and request an updated token. From here, we can tell the RTC engine to update the token without needing to first disconnect from the channel using AgoraRtcEngineKit.renewToken(:String).

Full Example

Be sure to use the other two parameters (response and err) when adding this to your own project, because they are helpful for ensuring that the response from your token server is valid, and they can help you debug any issues.

After you have a way to fetch the token, you need to send it up with the request to join the channel by using joinChannel (see Agora — joinChannelByToken).

To see a fully working iOS example that fetches the token from a server and also refreshes it upon expiry, take a look at this project.

The token in the above project is being fetched and applied in this file: AgoraToken.swift.

If you have Xcode installed, try the Agora-Swift-Token.playground file, found in the Agora-Token-Swift repository. You can interactively execute the above method on your own machine to see the token being retrieved from your server.

RTE Telehealth 2023
Join us for RTE Telehealth - a virtual webinar where we’ll explore how AI and AR/VR technologies are shaping the future of healthcare delivery.

Try Agora for Free

Sign up and start building! You don’t pay until you scale.
Try for Free
Get Started with Agora thumbnail