This doc will introduce how to implement the call invitation feature in the calling scenario.
Before you begin, make sure you complete the following:
You can achieve the following effect with the demo provided in this doc:
Home Page | Incoming Call Dialog | Waiting Page | Calling Page |
---|---|---|---|
![]() |
![]() |
![]() |
![]() |
Implementation of the call invitation is based on the Call invitation (signaling) feature provided by the in-app chat (hereafter referred to as ZIM SDK)
, which provides the capability of call invitation, allowing you to send, cancel, accept, and reject a call invitation.
The process of call invitation implemented based on this is as follows: (taking "Alice calls Bob, Bob accepts and connects the call" as an example)
Here is a brief overview of the solution:
The caller can send a call invitation to a specific user by calling the sendUserRequest
method and waiting for the callee's response.
onUserRequestStateChanged
, ZIMCallUserInfo
status is ZIMCallUserStateAccepted
.onUserRequestStateChanged
, ZIMCallUserInfo
status is ZIMCallUserStateRejected
.onUserRequestStateChanged
, ZIMCallUserInfo
status is ZIMCallUserStateTimeout
.endUserRequest
to end the call invitation during the waiting period.When the callee receives a call invitation, the callee will receive a callback notification via the onInComingUserRequestReceived
event and can choose to accept, reject, or not respond to the call.
acceptUserRequest
method.refuseUserRequest
method.onUserRequestEnded
.onInComingUserRequestTimeout
.If the callee accepts the invitation, the call will begin.
Later in this document, the complete call process will be described in detail.
func sendUserRequest(userList: [String], config: ZIMCallInviteConfig, callback: ZIMCallInvitationSentCallback?)
func addUserToRequest(invitees: [String], requestID: String, config: ZIMCallingInviteConfig, callback: ZIMCallingInvitationSentCallback?)
func cancelUserRequest(requestID: String, config: ZIMCallCancelConfig, userList: [String], callback: ZIMCallCancelSentCallback?)
func refuseUserRequest(requestID: String, config: ZIMCallRejectConfig, callback: ZIMCallRejectionSentCallback?)
func acceptUserRequest(requestID: String, config: ZIMCallAcceptConfig, callback: ZIMCallAcceptanceSentCallback?)
@objc optional func onInComingUserRequestReceived(requestID: String, info: ZIMCallInvitationReceivedInfo)
@objc optional func onInComingUserRequestTimeout(requestID: String, info: ZIMCallInvitationTimeoutInfo?)
@objc optional func onUserRequestStateChanged(info: ZIMCallUserStateChangeInfo, requestID: String)
@objc optional func onUserRequestEnded(info: ZIMCallInvitationEndedInfo, requestID: String)
If you have not used the ZIM SDK before, you can read the following section:
Integrate the SDK automatically with Swift Package Manager
Open Xcode and click "File > Add Packages..." in the menu bar, enter the following URL in the "Search or Enter Package URL" search box of the "Apple Swift Packages" pop-up window:
https://github.com/zegolibrary/zim-ios
Specify the SDK version you want to integrate in "Dependency Rule" (Recommended: use the default rule "Up to Next Major Version"), and then click "Add Package" to import the SDK. You can refer to Apple Documentation for more details.
After successful integration, you can use the Zim SDK like this:
import ZIM
Creating a ZIM instance is the very first step, an instance corresponds to a user logging in to the system as a client.
func initWithAppID(_ appID: UInt32, appSign: String?) {
let zimConfig: ZIMAppConfig = ZIMAppConfig()
zimConfig.appID = appID
zimConfig.appSign = appSign
self.zim = ZIM.shared()
if self.zim == nil {
self.zim = ZIM.create(with: zimConfig)
}
self.zim?.setEventHandler(self)
}
Later on, we will provide you with detailed instructions on how to use the ZIM SDK to develop the call invitation feature.
In most cases, you need to use multiple SDKs together. For example, in the call invitation scenario described in this doc, you need to use the zim sdk
to implement the call invitation feature, and then use the zego_express_engine sdk
to implement the calling feature.
If your app has direct calls to SDKs everywhere, it can make the code difficult to manage and troubleshoot. To make your app code more organized, we recommend the following way to manage these SDKs:
Create a ZIMService
class for the zim sdk
, which manages the interaction with the SDK and stores the necessary data. Please refer to the complete code in ZIMService.swift.
class ZIMService: NSObject {
// ...
func initWithAppID(_ appID: UInt32, appSign: String?) {
let zimConfig: ZIMAppConfig = ZIMAppConfig()
zimConfig.appID = appID
zimConfig.appSign = appSign ?? ""
self.zim = ZIM.shared()
if self.zim == nil {
self.zim = ZIM.create(with: zimConfig)
}
self.zim?.setEventHandler(self)
}
// ...
}
Similarly, create an ExpressService
class for the zego_express_engine sdk
, which manages the interaction with the SDK and stores the necessary data. Please refer to the complete code in ExpressService.swift.
class ExpressService: NSObject {
// ...
func initWithAppID(_ appID: UInt32, appSign: String) {
let profile = ZegoEngineProfile()
profile.appID = appID
profile.appSign = appSign
profile.scenario = .default
let config: ZegoEngineConfig = ZegoEngineConfig()
config.advancedConfig = ["notify_remote_device_unknown_status": "true", "notify_remote_device_init_status":"true"]
ZegoExpressEngine.setEngineConfig(config)
ZegoExpressEngine.createEngine(with: profile, eventHandler: self)
}
// ...
}
With the service, you can add methods to the service whenever you need to use any SDK interface.
class ZIMService: NSObject {
// ...
func connectUser(userID: String, userName: String, token: String?, callback: CommonCallback?) {
let user = ZIMUserInfo()
user.userID = userID
user.userName = userName
userInfo = user
zim?.login(with: user, token: token ?? "") { error in
callback?(Int64(error.code.rawValue), error.message)
}
}
}
ZegoSDKManager
to manage these services, as shown below. Please refer to the complete code in ZegoSDKManager.swift.class ZegoSDKManager: NSObject {
static let shared = ZegoSDKManager()
var expressService = ExpressService.shared
var zimService = ZIMService.shared
func initWithAppID(_ appID: UInt32, appSign: String) {
expressService.initWithAppID(appID, appSign: appSign)
zimService.initWithAppID(appID, appSign: appSign)
}
}
In this way, you have implemented a singleton class that manages the SDK services you need. From now on, you can get an instance of this class anywhere in your project and use it to execute SDK-related logic, such as:
ZegoSDKManager.shared.initWithAppID(appID,appSign)
ZegoSDKManager.shared.loginRoom(roomID, scenario, callback)
ZegoSDKManager.shared.logoutRoom()
Later, we will introduce how to add call invitation feature based on this.
When the caller initiates a 1v1 or group call, not only specifying the callee, but also passing on information to the callee is allowed, such as whether to initiate a video call or an audio-only call.
The sendUserRequest
method allows for passing a string type of extended information extendedData
. This extended information will be passed to the callee. You can use this method to allow the caller to pass any information to the callee.
In the example demo of this solution, you will use the [String : Any]
type to define the extendedData
of the call invitation, and you need to convert it to a string in JSON format and pass it to the callee when initiating the call. (See complete source code). The extendedData
includes the call type.
// 1v1 call
func sendVideoCallInvitation(_ targetUserID: String, callback: CallRequestCallback?) {
let callType: CallType = .video
if let currentCallData = currentCallData,
let callID = currentCallData.callID
{
addUserToRequest(userList: [targetUserID], requestID: callID, callback: callback)
} else {
let extendedData = getCallExtendata(type: callType)
sendUserRequest(userList: [targetUserID], extendedData: extendedData.toString() ?? "", type: callType, callback: callback)
}
}
// group call
func sendGroupVideoCallInvitation(_ targetUserIDs: [String], callback: CallRequestCallback?) {
let callType: CallType = .video
if let currentCallData = currentCallData,
let callID = currentCallData.callID
{
addUserToRequest(userList: targetUserIDs, requestID: callID, callback: callback)
} else {
let extendedData = getCallExtendata(type: callType)
sendUserRequest(userList: targetUserIDs, extendedData: extendedData.toString() ?? "", type: callType, callback: callback)
}
}
// sendUserRequest
func sendUserRequest(userList: [String], extendedData: String, type: CallType, callback: CallRequestCallback?) {
guard let localUser = ZegoSDKManager.shared.currentUser else { return }
ZegoSDKManager.shared.zimService.queryUsersInfo(userList) { fullInfoList, errorUserInfoList, error in
if error.code == .success {
self.currentCallData = ZegoCallDataModel()
let config = ZIMCallInviteConfig()
config.mode = .advanced
config.extendedData = extendedData
config.timeout = 60
ZegoSDKManager.shared.zimService.sendUserRequest(userList: userList, config: config) { requestID, sentInfo, error in
if error.code == .success {
let errorUser: [String] = sentInfo.errorUserList.map { userInfo in
userInfo.userID
}
let sucessUsers = userList.filter { userID in
return !errorUser.contains(userID)
}
if !sucessUsers.isEmpty {
self.currentCallData?.callID = requestID
self.currentCallData?.inviter = CallUserInfo(userID: localUser.id)
self.currentCallData?.type = type
self.currentCallData?.callUserList = []
} else {
self.clearCallData()
}
} else {
self.clearCallData()
}
guard let callback = callback else { return }
callback(error.code.rawValue, requestID)
}
} else {
guard let callback = callback else { return }
callback(error.code.rawValue, nil)
}
}
}
Note: The caller needs to check the error info in
ZIMServiceInviteUserCallBack
to determine if the call is successful and handle exception cases such as call failure due to network disconnection on the caller's phone.
In the 1v1 calling scenario, as a caller, after initiating the call, you will enter the call waiting page, where you can listen to the status changes of the call. See complete source code for details. The key code is as follows:
class CallWaitViewController: UIViewController {
// ...
override func viewDidLoad() {
super.viewDidLoad()
ZegoCallManager.shared.addCallEventHandler(self)
}
// ...
}
extension CallWaitingViewController: ZegoCallManagerDelegate {
// ...
func onInComingCallInvitationTimeout(requestID: String) {
self.dismiss(animated: true)
}
// ...
}
In the group call scenario, as a caller, after initiating the call, you will enter the calling page, where you can listen to the status changes of the call. See complete source code for details. The key code is as follows:
class CallingViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
ZegoCallManager.shared.addCallEventHandler(self)
//...
}
}
extension CallingViewController: ZegoCallManagerDelegate {
func onCallUserUpdate(userID: String, extendedData: String) {
//...
}
func onOutgoingCallInvitationAccepted(userID: String, extendedData: String) {
//...
}
func onCallUserQuit(userID: String, extendedData: String) {
//...
}
func onOutgoingCallInvitationTimeout(userID: String, extendedData: String) {
//...
}
func onCallEnd() {
ZegoCallManager.shared.leaveRoom()
self.dismiss(animated: true)
}
}
extension HomeViewController: ZegoCallManagerDelegate {
//...
func onCallEnd() {
callWaitingVC?.dismiss(animated: true)
ZegoIncomingCallDialog.hide()
}
//...
}
class CallingViewController: UIViewController, ZegoCallManagerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
ZegoCallManager.shared.addCallEventHandler(self)
//...
}
//...
func onCallEnd() {
self.dismiss(animated: true)
}
//...
}
endUserRequest
method. In the
endUserRequest
method, you are required to pass arequestID
.requestID
is a unique identifier for a call invitation that can be obtained from theZIMServiceCancelInviteCallBack
parameter of thesendUserRequest
method.
//1v1 calling scenario end call
class CallWaitingViewController: UIViewController {
// ...
@IBAction func handupButtonClick(_ sender: Any) {
guard let callID = ZegoCallManager.shared.currentCallData?.callID else { return }
ZegoCallManager.shared.endCall(callID, callback: nil)
self.dismiss(animated: true)
}
// ...
}
//group call scenario end call
class CallingViewController: UIViewController {
// ...
@objc func buttonClick(_ sender: UIButton) {
switch sender.tag {
case 100:
ZegoCallManager.shared.quitCall(ZegoCallManager.shared.currentCallData?.callID ?? "", callback: nil)
self.dismiss(animated: true)
case 101:
//...
case 102:
//...
case 103:
//...
case 104:
//...
default:
break
}
}
// ...
}
When user is in a call, user can call the inviteUserToJoinCall
add new callee to the current call.
@IBAction func addMemberClick(_ sender: Any) {
let addAlterView: UIAlertController = UIAlertController(title: "add member", message: nil, preferredStyle: .alert)
//...
let sureAction: UIAlertAction = UIAlertAction(title: "sure", style: .default) { action in
//...
ZegoCallManager.shared.inviteUserToJoinCall([userID], callback: nil)
}
//...
self.present(addAlterView, animated: true)
}
When the callee receives a call invitation, they will receive the callback notification via onInComingUserRequestReceived
.
To accept or reject the call invite, the callee can call the acceptCallRequest
or rejectCallRequest
method.
The callee can obtain the extendedData
passed by the caller in ZIMCallInvitationReceivedInfo
.
When the callee accepts or rejects the call invitation, they can use the extendedData
parameter in the interface to pass additional information to the caller, such as the reason for rejection being due to user rejection or a busy signal.
The callee needs to check the
errorInfo
incallback
to determine if the response is successful when calling the methods to accept or reject the call invite, and handle exception cases such as response failure due to network disconnection on the callee's phone.
Next, we will use the demo code to illustrate how to implement this part of the functionality.
ZegoIncomingCallDialog
will be triggered to let the callee decide whether to accept or reject the call.For details, see complete source code. The key code is as follows:
// If the callee is in the busy state: the invitation will be automatically rejected, and the caller will be informed that the callee is in the busy state.
class ZegoCallManager: ZIMServiceDelegate {
// ...
func onInComingUserRequestReceived(requestID: String, info: ZIMCallInvitationReceivedInfo) {
let callExtendedData = ZegoCallExtendedData.parse(extendedData: info.extendedData)
guard let callType = callExtendedData?.type,
let _ = ZegoSDKManager.shared.currentUser
else { return }
if !isCallBusiness(type: callType.rawValue) { return }
let inRoom: Bool = (ZegoSDKManager.shared.expressService.currentRoomID != nil)
let inviteeList: [String] = info.callUserList.map { user in
user.userID
}
if inRoom || (currentCallData != nil && currentCallData?.callID != requestID) {
for delegate in callEventHandlers.allObjects {
delegate.onInComingCallInvitationReceived?(requestID: requestID, inviter: info.inviter, inviteeList: inviteeList, extendedData: info.extendedData)
}
// ... see CallService's onInComingUserRequestReceived
return
}
}
}
// If the callee is not in the busy state: the `ZegoIncomingCallDialog` will be triggered to let the callee decide whether to accept or reject the call.
class CallService: NSObject, ZegoReciverCallEventHandle {
override init() {
super.init()
ZegoCallManager.shared.addCallEventHandler(self)
}
func onInComingCallInvitationReceived(requestID: String, inviter: String, inviteeList: [String], extendedData: String) {
let extendedDict: [String : Any] = extendedData.toDict ?? [:]
let callType: CallType? = CallType(rawValue: extendedDict["type"] as? Int ?? -1)
guard let callType = callType else { return }
// receive call
let inRoom: Bool = (ZegoSDKManager.shared.expressService.currentRoomID != nil)
if inRoom || (ZegoCallManager.shared.currentCallData?.callID != requestID) {
let extendedData: [String : Any] = ["type": callType.rawValue, "reason": "busy", "callID": requestID]
ZegoCallManager.shared.rejectCallInvitationCauseBusy(requestID: requestID, extendedData: extendedData.jsonString, type: callType, callback: nil)
return
}
//...
}
}
ZegoIncomingCallDialog
pops up, when the accept button is clicked, callAccept
method will be called and will receive 2
callback enter the CallingPage
.For details, see complete source code. The key code is as follows:
class ZegoIncomingCallDialog: UIView {
// ...
@IBOutlet weak var acceptButton: UIButton!
@IBOutlet weak var rejectButton: UIButton!
// ...
@IBAction func acceptButtonClick(_ sender: UIButton) {
guard let inviter = callData?.inviter,
let callID = callData?.callID
else { return }
ZegoCallManager.shared.acceptCallInvitation(requestID: callID) { requestID, error in
//...
}
}
}
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
ZegoCallManager.shared.addCallEventHandler(self)
//...
}
}
extension HomeViewController: ZegoCallManagerDelegate {
func onCallStart() {
callWaitingVC?.dismiss(animated: true)
showCallPage()
}
//...
}
ZegoIncomingCallDialog
pops up, when the reject button is clicked, callReject
method will be called.For details, see complete source code. The key code is as follows:
class ZegoIncomingCallDialog: UIView {
// ...
@IBOutlet weak var acceptButton: UIButton!
@IBOutlet weak var rejectButton: UIButton!
// ...
@IBAction func rejectButtonClick(_ sender: UIButton) {
guard let callID = callData?.callID else { return }
ZegoCallManager.shared.rejectCallInvitation(requestID: callID, callback: nil)
ZegoIncomingCallDialog.hide()
}
// ...
}
ZegoIncomingCallDialog
pops up, if the call invitation times out due to the callee's lack of response, the ZegoIncomingCallDialog
needs to disappear.For details, see complete source code. The key code is as follows:
extension HomeViewController: ZegoCallManagerDelegate {
// ...
func onInComingCallInvitationTimeout(requestID: String) {
//....
ZegoIncomingCallDialog.hide()
}
// ...
}
callInvitationReceived
:
func zim(_ zim: ZIM, callInvitationReceived info: ZIMCallInvitationReceivedInfo, callID: String)
ZIMCallInvitationReceivedInfo
inside the callInvitationReceived
:
public class ZIMCallInvitationReceivedInfo {
public int timeout;
public String inviter;
public String extendedData;
public ZIMCallInvitationReceivedInfo() {}
}
Interfaces used to accept and reject the call invite:
func callReject(with callID: String, config: ZIMCallRejectConfig, callback: @escaping ZIMCallRejectionSentCallback)
func callAccept(with callID: String, config: ZIMCallAcceptConfig, callback: @escaping ZIMCallAcceptanceSentCallback)
public class ZIMCallAcceptConfig: NSObject {
public var extendedData: String?
}
public class ZIMCallRejectConfig: NSObject {
public var extendedData: String?
}
public typealias ZIMCallAcceptanceSentCallback = (_ callID: String, _ errorInfo: ZIMError?) -> Void
public typealias ZIMCallRejectionSentCallback = (_ callID: String, _ errorInfo: ZIMError?) -> Void
Finally, you also need to check the user's busy status, similar to the busy signal logic when making a phone call.
A busy signal refers to the situation where, when you try to dial a phone number, the target phone is being connected by other users, so you cannot connect with the target phone. In this case, you usually hear a busy tone or see a busy line prompt.
In general, being called, calling, and being in a call are defined as busy states. In the busy state, you can only handle the current call invitation or call, and cannot accept or send other call invitations. The state transition diagram is as follows:
In the example demo, you can use ZegoSDKManager
to manage the user's busy status:
currentCallData
, or clear the call data of currentCallData
.// When startCall or CallInvitation Received
let callData = ZegoCallDataModel()
// When IncomingCallInvitation end, Timeout, etc.
ZegoCallManager.shared.clearCallData()
For details, see complete source code. The key code is as follows:
class CallService: NSObject, ZegoCallManagerDelegate {
// ...
func onInComingCallInvitationReceived(requestID: String, inviter: String, inviteeList: [String], extendedData: String) {
let extendedDict: [String : Any] = extendedData.toDict ?? [:]
let callType: CallType? = CallType(rawValue: extendedDict["type"] as? Int ?? -1)
guard let callType = callType else { return }
// receive call
let inRoom: Bool = (ZegoSDKManager.shared.expressService.currentRoomID != nil)
if inRoom || (ZegoCallManager.shared.currentCallData?.callID != requestID) {
let extendedData: [String : Any] = ["type": callType.rawValue, "reason": "busy", "callID": requestID]
ZegoCallManager.shared.rejectCallInvitationCauseBusy(requestID: requestID, extendedData: extendedData.jsonString, type: callType, callback: nil)
return
}
//...
}
}
After the callee accepts the call invitation, the caller will receive the callback notification via onUserRequestStateChanged
, and both parties can start the call.
You can refer to the implementation of the call page in Quick start, or you can directly refer to the demo's sample code included in this doc.
In this demo, we use
callID
as theroomID
forzego_express_sdk
. For information onroomID
, refer to Key concepts.
Resolution And Pricing Attention!
Please pay close attention to the relationship between video resolution and price when implementing video call, live streaming, and other video scenarios.
When playing multiple video streams in the same room, the billing will be based on the sum of the resolutions, and different resolutions will correspond to different billing tiers.
The video streams that are included in the calculation of the final resolution are as follows:
Before your app goes live, please make sure you have reviewed all configurations and confirmed the billing tiers for your business scenario to avoid unnecessary losses. For more details, please refer to Pricing.
Congratulations! Hereby you have completed the development of the call invitation feature.
If you have any suggestions or comments, feel free to share them with us via Discord. We value your feedback.