All Products
Search
Document Center

Intelligent Media Services:Integrate into iOS apps

Last Updated:Mar 05, 2025

This topic describes how to integrate AI Agents for messaging and conversation into your iOS application using the AICallKit SDK.

Prerequisites

  • Xcode 16.0 or later is recommended, with the latest official version preferred.

  • Cocoa Pods 1.9.3 or later.

  • A physical device running iOS 10.0 or later.

Integrate SDKs

target '你的Target' do

  # Integrate ApsaraVideo MediaBox SDK for Alibaba Real-Time Communication (ARTC). You can integrate AliVCSDK_ARTC, AliVCSDK_Standard, or AliVCSDK_InteractiveLive
  pod 'AliVCSDK_ARTC', '~> x.x.x'
  # Integrate AICallKit SDK
  pod 'ARTCAICallKit/Chatbot', '~> 2.1.0'

  # You need to integrate AliVCInteractionMessage with a minimum version of 1.5.0
  pod 'AliVCInteractionMessage', '~> 1.5.0'
  
  ...

end
Note

You can go to the official website to download ARTC SDK of the latest version.

Project configuration

  • Add microphone and camera permissions by opening the project info.Plist and adding NSMicrophoneUsageDescription and NSCameraUsageDescription.

  • Enable Background Modes in Signing & Capabilities within the project settings. Enabling background mode is strongly recommended to continue calls after entering the background. Otherwise, you must call the end call interface in your app.

Use SDKs

// Import SDK
import ARTCAICallKit

// Create an engine instance
let engine: ARTCAIChatEngineInterface = {
    return ARTCAICallEngineFactory.createChatEngine()
}()

// Configure callbacks
self.engine.delegate = self


// Start a conversation
// userId is recommended to use the user id after logging into your app
let userId = "xxx"
// Set deviceId
let deviceId = UIDevice.current.identifierForVendor?.uuidString
let userInfo = ARTCAIChatUserInfo(userId, deviceId)
// Set AI agent. The agentId cannot be nil
let agentInfo = ARTCAIChatAgentInfo(agentId: "xxx")
let sessionId = "\(userInfo.userId)_\(agentInfo.agentId)"
self.engine.startChat(userInfo: userInfo, agentInfo: agentInfo, sessionId: self.sessionId)


// End a conversation
// If there are multiple AI Agents for messaging and conversation, you do not need to log out when ending the current conversation. Set needLogout to false
self.engine.endChat(needLogout: false)
// Otherwise, set needLogout to false and call destroy to release resources
self.engine.endChat(needLogout: true)
self.engine.destroy()


// For examples of other feature calls, see the API description

// Handle callback events (only examples without core callback operations)
public func onRequestAuthToken(userId: String, responseBlock: @escaping (ARTCAIChatAuthToken?, NSError?) -> Void) {
    // Request AuthToken. This is triggered when ChatEngine needs to perform IM logon or when the IM logon AuthToken expires
    self.fetchAuthToken(userId: userId) { authToken, error in
        responseBlock(authToken, error)
    }
}

public func onEngineStateChange(state: ARTCAIChatEngineState) {
    // The connection status of the Chat AI Agent changes
}

public func onErrorOccurs(error: NSError, requestId: String?) {
    // If requestId is not empty, an error occurred during message processing
    if let _ = requestId {
        if error.aicall_code == .ChatTextMessageReceiveFailed {
            // An error occurred while processing the text message
            return
        }
        if error.aicall_code == .ChatVoiceMessageReceiveFailed {
            // An error occurred while processing the voice message
            return
        }
        
        if error.aicall_code == .ChatPlayMessageReceiveFailed {
            // An error occurred during playback
            return
        }
        
        return
    }

    // If requestId is empty, an error occurred in the engine
    if let code = error.aicall_code {
        if code == .TokenExpired {
            // Authentication expired
        }
        else if code == .AgentNotFound {
            // AI Agent not found (agent ID does not exist)
        }
        else if code == .KickedBySystem {
            // Kicked out by the system, causing the conversation to fail
        }
        else if code == .KickedByUserReplace {
            // The same name logon caused the call to fail
        }
    }

    // Handle other errors
}

public func onUserMessageUpdated(message: ARTCAIChatMessage) {
    // The message sent by the user needs to be updated
}

public func onReceivedMessage(message: ARTCAIChatMessage) {
    // A reply message from the Chat AI Agent is received. This callback is triggered when the AI Agent has a new reply or when the status of the message changes during the current reply process
}

public func onAgentResponeStateChange(state: ARTCAIChatAgentResponseState, requestId: String?) {
    // Received a response change from the Chat AI Agent
}

public func onMessagePlayStateChange(message: ARTCAIChatMessage, state: ARTCAIChatMessagePlayState) {
    // Received a message playback status change from the Chat AI Agent
}

API description

API overview

Class or protocol

API

Description

ARTCAIChatEngineInterface

Message conversation engine interface definition

state

Retrieve the engine connection status

userInfo

Retrieve the user information of the current session

sessionId

Retrieve the unique identifier of the current session

agentInfo

Retrieve the AI Agent information of the current session

agentResponeState

Retrieve the current AI Agent response status

voiceIdList

Retrieve the current voice list

delegate

Configures and queries callback events

templateConfig

Configures and queries TemplateConfig

userData

User-defined information that is eventually passed to the AI Agent

startChat

Start a chat session

endChat

End a chat session

sendMessage

Send a message. The current reply will be interrupted before sending (if in thinking & replying)

queryMessageList

Request the historical message list

interruptAgentResponse

Interrupt the current message reply

deleteMessage

Delete a message

startPlayMessage

Start playing the message content

stopPlayMessage

End the playback of the message

isPlayingMessage

Is it playing

startPushVoiceMessage

Start push-to-talk. Recording starts and is sent in real-time when pressed. Ensure that recording permission is enabled

finishPushVoiceMessage

End push-to-talk. Call when released to indicate that the current voice message has been sent and wait for the AI Agent to return the result

cancelPushVoiceMessage

Cancel push-to-talk. Call when released to indicate that the current voice message sending is canceled

destroy

Release resources

parseShareAgentChat

Parses the information about a shared intelligent agent

generateShareAgentChat

Starts a call with a shared intelligent agent

IARTCAIChatEngineCallback

Message conversation engine callback events

onErrorOccurs

An error occurred

onRequestAuthToken

Request AuthToken. This is triggered when ChatEngine needs to perform IM logon or when the IM logon AuthToken expires

onEngineStateChange

Received a change in the AI Agent connection status

onReceivedMessage

A reply message from the AI Agent is received. This callback is triggered when the AI Agent has a new reply or when the status of the message changes during the current reply process

onReceivedCustomMessage

Received a custom message

onUserMessageUpdated

The message sent by the user needs to be updated

onAgentResponeStateChange

Received a response change from the AI Agent

onMessagePlayStateChange

Received a message playback status change from the Chat AI Agent

ARTCAICallEngineFactory

An engine factory

createChatEngine

Create a default Chat AI Agent engine

ARTCAIChatEngineInterface

State

Retrieve the engine connection status.

var state: ARTCAIChatEngineState { get }

UserInfo

Retrieve the user information for the current session.

var userInfo: ARTCAIChatUserInfo? { get }

SessionId

Retrieve the unique identifier for the current session.

var sessionId: String? { get }

AgentInfo

Retrieve the AI Agent information for the current session.

var agentInfo: ARTCAIChatAgentInfo? { get }

AgentResponeState

Retrieve the current AI Agent response status.

var agentResponeState: ARTCAIChatAgentResponseState { get }

VoiceIdList

Retrieve the current voice list.

var voiceIdList: [String] { get }

Delegate

Configure and query callback events.

weak var delegate: ARTCAIChatEngineDelegate? { get set }

TemplateConfig

Configure and query TemplateConfig.

var templateConfig: ARTCAIChatTemplateConfig? { get set }

Userdata

Pass user-defined information to the AI Agent.

var userData: [String: Any]? { get set }

Startchat

Initiate a chat session.

func startChat(userInfo: ARTCAIChatUserInfo, agentInfo: ARTCAIChatAgentInfo, sessionId: String?)

Parameters

Parameter

Type

Description

userInfo

ARTCAIChatUserInfo

User information for the current session

agentInfo

ARTCAIChatAgentInfo

AI Agent information for the current session

sessionId

String?

The unique identifier of the current session. If empty, userId+agentId is used as the unique identifier

Endchat

Terminate a chat session.

func endChat(needLogout: Bool)

Parameters

Parameter

Type

Description

needLogout

Bool

Whether the current user needs to log out in real-time (setting it to false will reduce the connection time for the next startChat. You can set it to true when you no longer want to chat in the future)

Sendmessage

Send a message, interrupting the current reply if necessary.

func sendMessage(request: ARTCAIChatSendMessageRequest, completed:((_ msg: ARTCAIChatMessage?, _ error: NSError?) -> Void)?)

Parameters

Parameter

Type

Description

request

ARTCAIChatSendMessageRequest

The message content to be sent

completed

(_ msg: ARTCAIChatMessage?, _ error: NSError?) -> Void

Result callback

Querymessagelist

Request the historical message list.

func queryMessageList(request: ARTCAIChatMessageListRequest, completed:((_ msgList: [ARTCAIChatMessage]?, _ error: NSError?) -> Void)?)  

Parameters

Parameter

Type

Description

request

ARTCAIChatMessageListRequest

Request model

completed

(_ msgList: [ARTCAIChatMessage]?, _ error: NSError?) -> Void)?

Result callback

Interruptagentresponse

Interrupt the current message reply.

func interruptAgentResponse()

Deletemessage

Delete a message.

func deleteMessage(dialogueId: String, completed:((_ error: NSError?) -> Void)?)

Parameters

Parameter

Type

Description

dialogueId

String

Message Id

completed

(_ error: NSError?) -> Void)?

Result callback

Startplaymessage

Begin playback of a message.

func startPlayMessage(message: ARTCAIChatMessage, voiceId: String?, completed: ((NSError?) -> Void)?)

Parameters

Parameter

Type

Description

message

ARTCAIChatMessage

The message to be played

voiceId

voiceId

The voice to be played

completed

(_ error: NSError?) -> Void)?

Result callback

Stopplaymessage

Stop message playback.

func stopPlayMessage()

Isplayingmessage

Check if a message is currently playing.

func isPlayingMessage(dialogueId: String) -> Bool

Startpushvoicemessage

Initiate push-to-talk, sending the recording in real-time. Ensure recording permission is granted.

Returns true on success, false on failure due to reasons such as incorrect status or lack of recording permission.

func startPushVoiceMessage(request: ARTCAIChatSendMessageRequest) -> Bool

Parameters

Parameter

Type

Description

request

ARTCAIChatSendMessageRequest

The message content to be sent

Finishpushvoicemessage

Conclude push-to-talk, indicating the voice message has been sent and awaiting the AI Agent's response.

func finishPushVoiceMessage(completed:((_ msg: ARTCAIChatMessage) -> Void)?)

Parameters

Parameter

Type

Description

completed

(_ msg: ARTCAIChatMessage) -> Void)?

Result callback

CancelPushVoiceMessage

Cancel push-to-talk, indicating the voice message send has been aborted.

func cancelPushVoiceMessage()

Destroy

Release resources.

func destroy()

Parseshareagentchat

Parse shared intelligent agent information.

func parseShareAgentChat(shareInfo: String) -> ARTCAIChatAgentShareConfig?

Parameters

Parameter

Type

Description

shareInfo

String

Share information

GenerateShareAgentChat

Initiate a call with a shared intelligent agent.

func generateShareAgentChat(shareConfig: ARTCAIChatAgentShareConfig, userId: String, completed: ((_ agentInfo: ARTCAIChatAgentInfo?, _ authToken: ARTCAIChatAuthToken?, _ error: NSError?, _ reqId: String) -> Void)?)    

Parameters

Parameter

Type

Description

shareConfig

ARTCAIChatAgentShareConfig

Share information

userId

String

User id

completed

(_ agentInfo: ARTCAIChatAgentInfo?, _ authToken: ARTCAIChatAuthToken?, _ error: NSError?, _ reqId: String) -> Void)?

Result callback

ARTCAIChatEngineDelegate

Onerroroccurs

An error has occurred.

@objc optional func onErrorOccurs(error: NSError, requestId: String?)

Parameters

Parameter

Type

Description

error

NSError

Error message

requestId

String?

Message request Id. If not nil, the error belongs to a message error

OnRequestAuthToken

Request an AuthToken when ChatEngine needs to perform an IM logon or when the IM logon AuthToken expires.

@objc optional func onRequestAuthToken(userId: String, responseBlock: @escaping (_ authToken: ARTCAIChatAuthToken?, _ error: NSError?)->Void)

Parameters

OnEngineStateChange

Notification of a change in the engine connection status.

@objc optional func onEngineStateChange(state: ARTCAIChatEngineState)

Parameters

Parameter

Type

Description

state

ARTCAIChatEngineState

The current AI Agent connection status

Onreceivedmessage

Notification of a new reply or a change in the status of a message from the AI Agent.

@objc optional func onReceivedMessage(message: ARTCAIChatMessage)

Parameters

Parameter

Type

Description

message

ARTCAIChatMessage

Message object

Onreceivedcustommessage

Notification of a custom message received.

@objc optional func onReceivedCustomMessage(text: String)

Parameters

Parameter

Type

Description

text

String

Message content

Onusermessageupdated

Notification that a user-sent message needs updating.

@objc optional func onUserMessageUpdated(message: ARTCAIChatMessage)

Parameters

Parameter

Type

Description

message

ARTCAIChatMessage

Message object

OnAgentResponeStateChange

Notification of a response status change from the AI Agent.

@objc optional func onAgentResponeStateChange(state: ARTCAIChatAgentResponseState, requestId: String?)

Parameters

Parameter

Type

Description

state

ARTCAIChatAgentResponseState

Response status

requestId

String?

The current message session

Onmessageplaystatechange

Notification of a message playback status change from the Chat AI Agent.

@objc optional func onMessagePlayStateChange(message: ARTCAIChatMessage, state: ARTCAIChatMessagePlayState)

Parameters

Parameter

Type

Description

message

ARTCAIChatMessage

Message object

state

ARTCAIChatMessagePlayState

Playback status

ARTCAICallEngineFactory

Createchatengine

Create a default Chat AI Agent engine.

public static func createChatEngine() -> ARTCAIChatEngineInterface