iosswiftbearer-tokenagora.io

How do I create a channel and server token using AgoraRtcEngineKit in Swift?


I am following the Agora.io channel management guide for joining a channel using AgoraRtcEngineKit for iOS. It states that I should call createRtcChannel of the AgoraRtcEngineKit class to create an AgoraRtcChannel object with a channel ID. However, AgoraRtcEngineKit does not have a createRtcChannel method in Swift. The alternative is that I use Objective-C code, but this seems a little hacky.

Second, following the token generation reference, I need to generate a server token using RtcTokenBuilder. It states "your token needs to be generated on your own server, hence you are required to first deploy a token generator on the server." Ideally, I would be able to generate a token in Swift, but the only available languages for the source code is C++, Java, Python, PHP, Node.js, Go, Ruby. I assume I can do this with JavaScriptCore, but, like with the channel generation, this doesn't seem like an optimal solution.

Per the documentation:

What is the standard way to generate a channel and token to join channel using AgoraRtcEngineKit in iOS Swift via Agora.io?


Solution

  • I ultimately figured it out following this guide on deploying a Dynamic Key Server. You need to simply deploy a Heroku Dynamic Key server, which is in the TokenServer-nodeJS. Go to this deployment link and input your respective Agora.io APP_ID and APP_CERTIFICATE. Once the token server is deployed, we can use an HTTP get request to get the token as a response in JSON format which you can then parse with a framework like SwiftyJSON. Namely, once the server is running you replace below with your instance url and generate tokens using this endpoint: https://<heroku url>/access_token?channel=test&uid=1234

    Using this instance url example:

    let request = AF.request("https://matchr-token.herokuapp.com/access_token?channel=test&uid=1234")
    
    request.responseJSON { (response) in
    
        guard let tokenDict = response.value as! [String : Any]? else { return }
    
        let token = tokenDict["token"] as! String
    
        // use the generated token here
    
     }
    

    There are two parameters in this instance url, i.e. the channel and uid, which can be set as needed to generate a unique token.