Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WEBRTC-2470: Improve iOS SDK Documentation #168

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 60 additions & 9 deletions TelnyxRTC/Telnyx/TxClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -161,9 +161,25 @@ public class TxClient {
}
}

/// When implementing CallKit framework, audio has to be manually handled.
/// Set this property to TRUE when `provider(CXProvider, didActivate: AVAudioSession)` is called on your CallKit implementation
/// Set this property to FALSE when `provider(CXProvider, didDeactivate: AVAudioSession)` is called on your CallKit implementation
/// Controls the audio device state when using CallKit integration.
/// This property manages the WebRTC audio session activation and deactivation.
///
/// When implementing CallKit, you must manually handle the audio session state:
/// - Set to `true` in `provider(_:didActivate:)` to enable audio
/// - Set to `false` in `provider(_:didDeactivate:)` to disable audio
///
/// Example usage with CallKit:
/// ```swift
/// extension CallKitProvider: CXProviderDelegate {
/// func provider(_ provider: CXProvider, didActivate audioSession: AVAudioSession) {
/// telnyxClient.isAudioDeviceEnabled = true
/// }
///
/// func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) {
/// telnyxClient.isAudioDeviceEnabled = false
/// }
/// }
/// ```
public var isAudioDeviceEnabled : Bool {
get {
return RTCAudioSession.sharedInstance().isAudioEnabled
Expand All @@ -178,17 +194,28 @@ public class TxClient {
}
}


public func enableAudioSession(audioSession: AVAudioSession){
/// Enables and configures the audio session for a call.
/// This method sets up the appropriate audio configuration and activates the session.
///
/// - Parameter audioSession: The AVAudioSession instance to configure
/// - Important: This method should be called when starting a call or when audio is needed
public func enableAudioSession(audioSession: AVAudioSession) {
setupCorrectAudioConfiguration()
setAudioSessionActive(true)
}

public func disableAudioSession(audioSession: AVAudioSession){
/// Disables and resets the audio session.
/// This method cleans up the audio configuration and deactivates the session.
///
/// - Parameter audioSession: The AVAudioSession instance to reset
/// - Important: This method should be called when ending a call or when audio is no longer needed
public func disableAudioSession(audioSession: AVAudioSession) {
resetAudioConfiguration()
setAudioSessionActive(false)
}

/// The current audio route configuration.
/// This provides information about the active input and output ports.
let currentRoute = AVAudioSession.sharedInstance().currentRoute

/// Client must be registered in order to receive or place calls.
Expand All @@ -208,6 +235,13 @@ public class TxClient {
setupAudioRouteChangeMonitoring()
}

/// Sets up monitoring for audio route changes (e.g., headphones connected/disconnected,
/// Bluetooth device connected/disconnected).
///
/// This method registers for AVAudioSession route change notifications to:
/// - Track when audio devices are connected or disconnected
/// - Monitor changes in the active audio output
/// - Update the speaker state accordingly
private func setupAudioRouteChangeMonitoring() {
NotificationCenter.default.addObserver(
self,
Expand All @@ -216,6 +250,23 @@ public class TxClient {
object: nil)
}

/// Handles audio route change notifications from the system.
///
/// This method processes audio route changes and:
/// - Updates the internal speaker state
/// - Notifies observers about audio route changes
/// - Manages audio routing between available outputs
///
/// The method posts an "AudioRouteChanged" notification with:
/// - isSpeakerEnabled: Whether the built-in speaker is active
/// - outputPortType: The type of the current audio output port
///
/// Common route change reasons handled:
/// - .categoryChange: Audio session category was changed
/// - .override: Route was overridden by the system or user
/// - .routeConfigurationChange: Available routes were changed
///
/// @objc attribute is required for NotificationCenter selector
@objc private func handleAudioRouteChange(notification: Notification) {
guard let userInfo = notification.userInfo,
let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
Expand All @@ -226,7 +277,7 @@ public class TxClient {
let session = AVAudioSession.sharedInstance()
let currentRoute = session.currentRoute

// Check if we have any output ports
// Ensure we have at least one output port
guard let output = currentRoute.outputs.first else {
return
}
Expand All @@ -235,11 +286,11 @@ public class TxClient {

switch reason {
case .categoryChange, .override, .routeConfigurationChange:
// Update speaker state based on current output
// Update internal speaker state based on current output
let isSpeaker = output.portType == .builtInSpeaker
_isSpeakerEnabled = isSpeaker

// Notify UI of the change
// Notify observers about the route change
NotificationCenter.default.post(
name: NSNotification.Name("AudioRouteChanged"),
object: nil,
Expand Down
74 changes: 52 additions & 22 deletions TelnyxRTC/Telnyx/TxClientDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,47 +8,77 @@

import Foundation

/// Delegate protocol asociated with the TxClient
/// Methods for receiving TxClient events.
/// The TxClientDelegate protocol defines methods for receiving events and updates from a TxClient instance.
/// Implement this protocol to handle various states and events in your WebRTC-enabled application,
/// including connection status, call state changes, and push notifications.
///
/// ## Usage Example:
/// ```swift
/// class CallHandler: TxClientDelegate {
/// func onSocketConnected() {
/// print("Connected to Telnyx backend")
/// }
///
/// func onIncomingCall(call: Call) {
/// // Handle incoming call
/// call.answer()
/// }
///
/// // Implement other required methods...
/// }
/// ```
public protocol TxClientDelegate: AnyObject {

/// Tells the delegate when the Telnyx Client has successfully connected to the Telnyx Backend
/// Called when the WebSocket connection to Telnyx's backend is established.
/// This indicates a successful network connection, but the client may not be fully ready yet.
/// Wait for `onClientReady` before initiating calls.
func onSocketConnected()

/// Tells the delegate when the Telnyx Client has disconnected from the Telnyx Backend
/// Called when the WebSocket connection to Telnyx's backend is lost or closed.
/// The client will automatically attempt to reconnect unless explicitly disconnected.
func onSocketDisconnected()

/// Tells the delegate when there's an error in the Telnyx Client
/// - Parameter error: error occurred inside the Telnyx Client
/// Called when an error occurs in the TxClient.
/// - Parameter error: The error that occurred. Check the error type and message for details.
/// Common errors include authentication failures and network connectivity issues.
func onClientError(error: Error)

/// Tells the delegate that the The Telnyx Client is ready to be used.
/// Has successfully connected and logged in
/// Called when the client has successfully connected AND authenticated.
/// The client is now ready to make and receive calls.
/// This is the appropriate time to enable UI elements for calling functionality.
func onClientReady()

/// Called when push notification status changes for the current user.
/// - Parameters:
/// - success: Whether the push notification operation succeeded
/// - message: Descriptive message about the operation result
func onPushDisabled(success: Bool, message: String)

/// Push notification is disabled for the current user
func onPushDisabled(success:Bool,message:String)

/// Tells the delegate that the Telnyx Client session has been updated.
/// - Parameter sessionId: The new sessionId assigned to the client connection.
/// Called when the client's session is updated, typically after a reconnection.
/// - Parameter sessionId: The new session identifier for the connection.
/// Store this ID if you need to track or debug connection issues.
func onSessionUpdated(sessionId: String)

/// Tells the delegate that a call has been updated.
/// Called whenever a call's state changes (e.g., ringing, answered, ended).
/// - Parameters:
/// - callState: The new call state
/// - callId: The UUID of the affected call
/// - callState: The new state of the call (NEW, CONNECTING, RINGING, ACTIVE, HELD, DONE)
/// - callId: The unique identifier of the affected call
/// Use this to update your UI to reflect the current call state.
func onCallStateUpdated(callState: CallState, callId: UUID)

/// Tells the delegate that someone is calling
/// - Parameter call: The call object of the incoming call.
/// Called when a new incoming call is received.
/// - Parameter call: The Call object representing the incoming call.
/// You can use this object to answer or reject the call.
func onIncomingCall(call: Call)

/// Tells the delegate that a call has ended
/// - Parameter callId: the UUID of the call that has ended.
/// Called when a remote party ends the call.
/// - Parameter callId: The unique identifier of the ended call.
/// Use this to clean up any call-related UI elements or state.
func onRemoteCallEnded(callId: UUID)

/// Tells the delegate that an INVITE has been received for the incoming push
/// - Parameter call: The call object of the incoming call.
/// Called when a push notification triggers an incoming call.
/// - Parameter call: The Call object created from the push notification data.
/// This is specifically for handling calls that arrive via push notifications
/// when the app is in the background.
func onPushCall(call: Call)
}
Loading
Loading