Swift
電話の受信
これで呼び出しインターフェイスが構築できたので、次は呼び出しを受けるために必要なコードを追加することができる。その VGVoiceClientDelegate には、着信招待があったときに呼び出される関数がある。まず、クライアントのデリゲートを CallViewController's viewDidLoad 関数である:
self.client.delegate = self
そして、最後に CallViewController.swift ファイルに適合性を追加する。 VGVoiceClientDelegate.
extension CallViewController: VGVoiceClientDelegate {
func voiceClient(_ client: VGVoiceClient, didReceiveInviteForCall callId: String, from caller: String, withChannelType type: VGVoiceChannelType) {
DispatchQueue.main.async { [weak self] in
self?.displayIncomingCallAlert(callID: callId, caller: caller)
}
}
func voiceClient(_ client: VGVoiceClient, didReceiveInviteCancelForCall callId: String, with reason: VGVoiceInviteCancelReason) {
DispatchQueue.main.async { [weak self] in
self?.dismiss(animated: true)
}
}
func voiceClient(_ client: VGVoiceClient, didReceiveHangupForCall callId: String, withQuality callQuality: VGRTCQuality, reason: VGHangupReason) {
self.callID = nil
self.setHangUpButtonHidden(true)
self.setStatusLabelText("Ready to receive call...")
}
func client(_ client: VGBaseClient, didReceiveSessionErrorWith reason: VGSessionErrorReason) {
let reasonString: String!
switch reason {
case .tokenExpired:
reasonString = "Expired Token"
case .pingTimeout, .transportClosed:
reasonString = "Network Error"
default:
reasonString = "Unknown"
}
self.setStatusLabelText(reasonString)
}
}
着信招待があった場合、 didReceiveInviteForCall が呼び出される。着呼側が通話を終了した場合、 didReceiveHangupForCall が呼び出される。招待がキャンセルされた場合 didReceiveInviteCancelForCall が呼ばれる。
次に displayIncomingCallAlert 関数の CallViewController クラスである:
func displayIncomingCallAlert(callID: String, caller: String) {
let alert = UIAlertController(title: "Incoming call from", message: caller, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Answer", style: .default, handler: { _ in
self.client.answer(callID) { error in
if error == nil {
self.setHangUpButtonHidden(false)
self.setStatusLabelText("On a call with \(caller)")
self.callID = callID
} else {
self.setStatusLabelText(error?.localizedDescription)
}
}
}))
alert.addAction(UIAlertAction(title: "Reject", style: .destructive, handler: { _ in
self.client.reject(callID) { error in
if let error {
self.setStatusLabelText(error.localizedDescription)
}
}
}))
self.present(alert, animated: true, completion: nil)
}
について displayIncomingCallAlert 関数は、呼び出しIDと呼び出し元をパラメータとして受け取る。関数内の UIAlertAction を割り当てます。 callID を先ほどのプロパティに追加すると、電話を切るボタンが表示されるようになります。通話終了関数を CallViewController クラスである:
@objc private func endCall() {
guard let callID else { return }
client.hangup(callID) { error in
if error == nil {
self.callID = nil
self.setHangUpButtonHidden(true)
self.setStatusLabelText("Ready to receive call...")
}
}
}
次のステップでは、電話をかけるために必要なコードを追加する。