Skip to content

Hướng dẫn sử dụng

Hướng dẫn sử dụng VBot iOS SDK.

Cấu hình dự án

Bật Voip trong dự án Xcode

Chọn Xcode Project → Capabilities

Thêm Background ModesPush Notifications

Background Modes, Bật Audio, AirPlay, and Picture in Picture | Voice over IP | Background Fetch | Remote Notifications

Mở tệp info.plist và thêm key sau

swift
<key>NSMicrophoneUsageDescription</key>
<string>Microphone access is necessary to be able to make calls.</string>

Lưu ý:

Khi khởi chạy dự án mà Xcode trả về lỗi

“Sandbox: rsync.samba (13105) deny(1) file-write-create”

Thực hiện chỉnh sửa sau:

Trong Build Settings, tìm User Script Sandboxing: Chọn No

Sử dụng SDK

AppDelegate.swift

Khởi tạo

Trong hàm application didFinishLaunchingWithOptions, gọi hàm khởi tạo VBotPhone và khởi tạo voipRegistry:

swift
// Khởi tạo đầy đủ với các cấu hình tùy chọn
let config = VBotConfig(
    supportPopupCall: false,            // Mặc định: false. Cho phép hiển thị popup cuộc gọi.
    includesCallsInRecents: true,       // Mặc định: false. Cho phép lưu lịch sử cuộc gọi vào nhật ký cuộc gọi hệ thống qua CallKit.
    iconTemplateImageData: UIImage(named: "callkit-icon")?.pngData(), // Ảnh icon hiển thị trên giao diện CallKit.
    environment: .production,           // Môi trường API. Mặc định là .production.
    customBaseUrl: nil                  // URL API tùy chỉnh nếu muốn cấu hình thủ công (ghi đè cấu hình môi trường).
)

VBotPhone.sharedInstance.setup(with: config)

voipRegistry = PKPushRegistry(queue: .main)
voipRegistry!.desiredPushTypes = [.voIP]
voipRegistry!.delegate = self

Trong đó:

  • supportPopupCall: Cho phép hoặc từ chối hiển thị popup cuộc gọi của SDK.
  • includesCallsInRecents: Hiển thị lịch sử cuộc gọi trong app Điện thoại của iOS.
  • iconTemplateImageData: Icon được hiển thị trong màn hình cuộc gọi CallKit.
  • environment: Chỉ định môi trường kết nối API.
  • customBaseUrl: Đường dẫn API URL tùy chọn nếu bạn muốn kết nối trực tiếp đến endpoint riêng. Ghi đè cấu hình từ environment.

iOS History Call handle

Nếu trong VBotConfig có set includesCallsInRecents là true thì trong app Phone của iOS sẽ hiển thị lịch sử cuộc gọi.

Khi khách hàng tap vào 1 lịch sử cuộc gọi, app sẽ mở ra. Hãy dùng code sau để handle

swift
import Intents

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {

        switch userActivity.activityType {
        case "INStartAudioCallIntent":
            return handleStartCallIntent(
                INStartAudioCallIntent.self,
                userActivity: userActivity,
                contacts: \.contacts,
            )

        case "INStartCallIntent":
            if #available(iOS 13.0, *) {
                return handleStartCallIntent(
                    INStartCallIntent.self,
                    userActivity: userActivity,
                    contacts: \.contacts,
                )
            } else {
                return false
            }

        default:
            return false
        }
    }

private func handleStartCallIntent<T: INIntent>(
        _ intentType: T.Type,
        userActivity: NSUserActivity,
        contacts: KeyPath<T, [INPerson]?>,
    ) -> Bool {
        let intent = userActivity.interaction?.intent

        guard let intent = intent as? T else {
            return false
        }

        if let person =  intent[keyPath: contacts]?.first {
            let displayName = person.displayName

            let result = VBotPhone.sharedInstance.getCallIntentFromUserActivity(displayName)
            // result này chứa name và number của người gọi. Từ đây app có thể dùng hàm startOutgoingCall để thực hiện cuộc gọi đi
        }

        return true
    }

Cuộc gọi đến

Thêm hàm lắng nghe sự kiện của PushKit (Thông báo cuộc gọi) và AppDelegate

swift
import PushKit

extension AppDelegate: PKPushRegistryDelegate {
    nonisolated func pushRegistry(_ registry: PKPushRegistry, didUpdate pushCredentials: PKPushCredentials, for type: PKPushType) {

            guard let token = registry.pushToken(for: .voIP) else {
                // Không lấy được token
                return
            }

            let pushToken = token.map { String(format: "%.2hhx", $0) }.joined()

            // Lưu token này lại, dùng khi connect account
            // savePushToken(pushToken)


    }

    nonisolated func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType, completion: @escaping () -> Void) {

        // Nếu payload có loại là .voIP thì gọi hàm startIncomingCall để khởi tạo cuộc gọi
        if type == .voIP {
            VBotPhone.sharedInstance.startIncomingCall(
                payload: payload,
                completion: completion
            )

        } else {
            completion()
        }

    }

}

Connect SDK

SWIFT
VBotPhone.sharedInstance.connect(token: token, pushkitToken: pushKitToken) { displayName, error in
	if let error = error as NSError? {
		// login error
		return
	}
    // login successful
}
SIPendedBy
400–402, 405–408, 412–413, 416, 500server
403, 409, 411, 486, 603callee
404, 410, 414, 480, 502carrier
415system
487caller

Trong đó:

  • token: Token SDK của tài khoản VBot
  • pushkitToken: Pushkit token đã lưu từ bước trước
  • error: Lỗi trả về khi đăng nhập không thành công

Disconnect SDK

SWIFT
VBotPhone.sharedInstance.disconnect { error in
	if let error = error as NSError? {
		// logout error
		return
	}
	 // logout error
}

Lấy danh sách hotline

SWIFT
VBotPhone.sharedInstance.getHotlines { hotlines, error in
	if error != nil {
		// get hotline error
		return
	}
	// get hotline successful
}

Gọi đi

swift
VBotPhone.sharedInstance.startOutgoingCall(
    displayName: "Nguyễn Văn A",
    number: "0901234567",
    hotline: "1900xxxx",
    externalCallId: "ext-call-123"  // Mã định danh cuộc gọi từ hệ thống ngoài (Tùy chọn)
) { success, error in
    if success {
        // Bắt đầu cuộc gọi đi thành công
    } else {
        // Lỗi khởi tạo cuộc gọi đi (lỗi nằm trong biến error)
    }
}

Trong đó:

  • displayName: Tên người nhận hiển thị trên CallKit.

  • number: Số điện thoại cần gọi.

  • hotline: Số hotline sử dụng.

  • externalCallId (tùy chọn): Mã cuộc gọi từ hệ thống bên ngoài, dùng để liên kết dữ liệu cuộc gọi.

    Giá trị externalCallId phải thỏa các điều kiện sau:
    • Độ dài tối đa: 32 ký tự.
    • Ký tự hợp lệ: chữ thường (az) và chữ số (09).
    • Không chứa ký tự đặc biệt, chữ in hoa hoặc khoảng trắng.

Gác máy

SWIFT
// Tắt call
VBotPhone.sharedInstance.endCall { error in
	if let error = error as NSError? {
		return
	}
}

Các hành động khác trong cuộc gọi

SWIFT
// Bật tắt mic
VBotPhone.sharedInstance.muteCall()

// Bật tắt loa ngoài
VBotPhone.sharedInstance.onOffSpeaker()

Lắng nghe các sự kiện (Delegate)

Đăng ký nhận các sự kiện cuộc gọi:

swift
// Đăng ký nhận delegate
VBotPhone.sharedInstance.addDelegate(self)

// Hủy đăng ký nhận delegate
deinit {
    VBotPhone.sharedInstance.removeDelegate(self)
}

Các delegate method được cung cấp bởi VBotPhoneDelegate:

swift
protocol VBotPhoneDelegate {
    // Trạng thái cuộc gọi thay đổi
    func callStateChanged(state: VBotCallState)

    // Cuộc gọi đi đã bắt đầu
    func callStarted()

    // Cuộc gọi đến được chấp nhận (Khi user chọn chấp nhận cuộc gọi)
    func callAccepted()

    // Cuộc gọi kết thúc, đi kèm nguyên nhân và bên kết thúc cuộc gọi
    func callEnded(reason: VBotEndCallReason, endedBy: VBotCallEndParty)

    // Trạng thái quyền truy cập microphone
    func microphonePermission(status: AVAudioSession.RecordPermission)

    // Trạng thái tắt/mở âm microphone thay đổi
    func callMuteStateDidChange(muted: Bool)

    // Nhận externalCallId (chỉ gọi 1 lần duy nhất khi bắt đầu cuộc gọi có chứa ID này, nếu không nil hoặc không rỗng)
    func didReceiveExternalCallId(_ externalCallId: String)

    // Yêu cầu hiển thị giao diện cuộc gọi
    func showCallVC()

    // Yêu cầu quay lại giao diện cuộc gọi
    func returnToCallVC()

    // Yêu cầu ẩn giao diện cuộc gọi
    func hideCallVC()

    // Mất kết nối mạng
    func networkIsUnreachable()

    // Kết nối mạng thay đổi
    func internetConnectionChanged()
}

Xem thêm

VBotEndCallReason

Enum nguyên nhân kết thúc cuộc gọi, nhận qua callEnded(reason:endedBy:). Kiểu Int (@objc), truy cập giá trị số qua reason.rawValue, tên ổn định qua reason.key và mô tả qua reason.description. endedByVBotCallEndParty (caller, callee, system, server, carrier, unknown). Callback cũ callEnded(reason:) vẫn tương thích ngược.

CaserawValueÝ nghĩa
normaly1000Cuộc gọi kết thúc bình thường
busy1001Máy bận
timeOut1004Hết thời gian chờ kết nối
noPushToken1018Chưa đăng ký push notification
notReadyForStartCall2002Chưa sẵn sàng để gọi đi / khởi tạo không thành công
invalidPhoneNumber2004Số điện thoại không hợp lệ
noDataFromServer2005Không có dữ liệu từ máy chủ
endCallBeforeServerStartCall2006Cuộc gọi kết thúc khi chưa kết nối
noCallCreated2007Lỗi khi khởi tạo cuộc gọi
dataInvalid2008Dữ liệu không hợp lệ
noVBotUser2009Không tìm thấy thông tin tài khoản
authenticatedFailed2010Xác thực thất bại
anotherCallInProgress2011Đang có cuộc gọi khác
decline2013Từ chối cuộc gọi
temporarilyUnavailable2014Không liên lạc được
reportNewIncomingCallFailed2016Không thể tiếp nhận cuộc gọi đến
alertDataNotFound2017Dữ liệu thông báo không hợp lệ
setupEndpointFailed2019Khởi tạo dịch vụ gọi thất bại
requestCallKitActionFailed2020Thực thi hành động cuộc gọi thất bại
noAccount2022Tài khoản chưa được cấu hình
incomingCallTimeout2023Cuộc gọi đến hết thời gian chờ
incorrectInformation2024Thông tin không chính xác
unauthenticated2025Chưa xác thực
insufficientBalance2026Số dư không đủ
recipientBlocksCalls2027Người nhận chặn cuộc gọi
destinationNotFound2028Không tìm thấy số đích
callIntervalNotAllowed2029Không được phép gọi trong khung giờ này
memberNotActivated2030Thành viên chưa kích hoạt
memberNotInProject2031Thành viên không thuộc dự án
doNotDisturb2032Không làm phiền
destinationGone2033Số đích không còn tồn tại
recipientAbsent2034Người nhận vắng mặt
packageExpired2035Gói cước đã hết hạn
hotlineTelcoNotSupported2036Hotline không hỗ trợ nhà mạng
telcoNotFound2037Không tìm thấy nhà mạng
invalidParameter2038Tham số không hợp lệ
projectExpired2039Dự án đã hết hạn
callerCanceled2040Người gọi đã hủy
connectionError2041Lỗi kết nối
transmissionError2042Lỗi đường truyền
unknownError9996Lỗi chưa xác định
microphonePermissionDenied9999Chưa cấp quyền microphone
swift
func callEnded(reason: VBotEndCallReason, endedBy: VBotCallEndParty) {
    switch reason {
    case .normaly:
        // Cuộc gọi kết thúc bình thường
        break
    case .busy, .decline, .temporarilyUnavailable:
        // Đầu bên kia không nhận cuộc gọi
        break
    default:
        print("Cuộc gọi kết thúc: \(reason.key), bởi \(endedBy.key)")
    }
}

Bảng mã trên cũng dùng cho lỗi trả về từ các hàm SDK: lỗi là NSError với code trùng rawValue tương ứng.

swift
VBotPhone.sharedInstance.startOutgoingCall(
    displayName: "Nguyễn Văn A",
    number: "0901234567",
    hotline: "1900xxxx"
) { success, error in
    guard let error = error else { return }

    if error.code == VBotEndCallReason.anotherCallInProgress.rawValue {
        // Đang có cuộc gọi khác
    }
    print("Gọi đi thất bại: \(error.localizedDescription)")
}

Đối chiếu với Android SDK

Android SDK dùng enum VBotEndCallReason với tên case và mã số giống hoàn toàn bảng trên, nên logic xử lý mã lỗi dùng chung được cho cả hai nền tảng.


Sử dụng với Objective-C

SDK tương thích hoàn toàn để sử dụng từ dự án Objective-C.

1. Import Module

Import module trong tệp .m hoặc .mm của bạn:

objc
@import VBotPhoneSDK;

2. Khởi tạo SDK trong AppDelegate

objc
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSData *iconData = UIImagePNGRepresentation([UIImage imageNamed:@"callkit-icon"]);

    VBotConfig *config = [[VBotConfig alloc] initWithSupportPopupCall:NO
                                               includesCallsInRecents:YES
                                                iconTemplateImageData:iconData
                                                          environment:VBotEnvironmentProduction
                                                        customBaseUrl:nil];

    [[VBotPhone sharedInstance] setupWith:config];
    return YES;
}

3. Thực hiện cuộc gọi đi (Outgoing Call)

objc
[[VBotPhone sharedInstance] startOutgoingCallWithDisplayName:@"Nguyễn Văn A"
                                                      number:@"0901234567"
                                                     hotline:@"1900xxxx"
                                              externalCallId:@"ext-call-123" // nil nếu không sử dụng
                                                  completion:^(BOOL success, NSError * _Nullable error) {
        if (success) {
            NSLog(@"Gọi đi thành công");
        } else {
            NSLog(@"Gọi đi thất bại với lỗi: %@", error.localizedDescription);
        }
    }];

4. Nhận sự kiện cuộc gọi qua Delegate

objc
@interface ViewController () <VBotPhoneDelegate>
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[VBotPhone sharedInstance] addDelegate:self];
}

- (void)dealloc {
    [[VBotPhone sharedInstance] removeDelegate:self];
}

#pragma mark - VBotPhoneDelegate

- (void)callStateChangedWithState:(enum VBotCallState)state {
    NSLog(@"Trạng thái cuộc gọi thay đổi: %ld", (long)state);
}

- (void)callStarted {
    NSLog(@"Cuộc gọi đi đã bắt đầu");
}

- (void)callAccepted {
    NSLog(@"Cuộc gọi đã được chấp nhận");
}

- (void)callEndedWithReason:(enum VBotEndCallReason)reason
                     endedBy:(enum VBotCallEndParty)endedBy {
    NSLog(@"Cuộc gọi kết thúc: %@, bởi %@", reason.key, endedBy.key);
}

- (void)didReceiveExternalCallId:(NSString *)externalCallId {
    NSLog(@"Nhận được External Call ID: %@", externalCallId);
}

@end