WebRTC iOS integration guide adding video calls to applications with secure connections

Key takeaways

• WebRTC on iOS is five moving parts, not one. A signaling channel, STUN, TURN, the WebRTC framework itself, and the iOS plumbing (CallKit + PushKit + AVAudioSession). Skip any of them and what you ship is a demo.

• P2P only scales to 2–3 callers. From 4 callers up you need an SFU (mediasoup, LiveKit, Janus, or Pion). MCU exists, but in 2026 it’s the wrong default because the CPU cost is too high.

• iOS WebRTC gets hardware video only for H.264. The Stasel build (M157, November 2026) also carries VP8, VP9 and AV1, but in software (more CPU and battery), and it ships no HEVC encoder or decoder. For mixed browser calls, prefer H.264: H.264 simulcast works on iPhone, while SVC (VP9/AV1 layers) runs only in software.

• Build < 1M minutes/month? Use an SDK. Build > 5M minutes/month? Self-host. Against Agora (~$4,000/month at 1M HD minutes) self-hosting still wins by an order of magnitude. Against LiveKit Cloud the minutes bill alone looks close after Hetzner’s June 2026 repricing, but at 720p LiveKit’s data-transfer charges add several times that (our estimate: ~$1,300/month at 1M minutes), so count bandwidth and your DevOps time before you decide. Features rarely settle it; the real question is who owns the SLA at 3am.

• The native iOS bits are where projects fail. CallKit + PushKit + AVAudioSession state corruption causes more bugs than the WebRTC framework itself. Budget two engineering weeks for iOS plumbing alone, whichever SDK you pick.

Updated November 2026: Stasel WebRTC M157 (5 November), Apple’s April 2026 rule that every App Store upload use the iOS 26 SDK (so the VoIP-push termination rule now hits every update), the iOS 26 CallKit Recents change for generic handles, and LiveKit’s data-transfer allowances.

More on this topic: see our complete guide, WebRTC in Android: SDKs, Capture, Compose UI (2026).

Why Fora Soft wrote this guide

We’ve shipped video and audio streaming software across 250+ projects since 2005, and WebRTC has been our default real-time stack on iOS since the framework stabilised on the Apple platform. The guide below is the playbook our iOS team uses internally: the bits we wish someone had written down when we started, and the traps that cost us weeks the first time around.

For context: we built the WebRTC HD video classroom inside BrainCert (4× Brandon Hall winner, 100K+ users), the HIPAA-compliant doctor-patient telemedicine flow on iOS for CirrusMED and Cloud Doctors (Brazil’s largest telemedicine platform), and the live debate iOS app for Ariuum. We’ve made every mistake at least once, and this article is what we know now.

The structure follows the order in which you’ll actually need it: what WebRTC is on iOS, the architecture decision, the iOS-specific plumbing, build-vs-buy with concrete numbers, the call flow in Swift, and the ten or so traps that ship bugs into production. If you only have time for two sections, read “The five iOS-specific moving parts” and “CallKit + PushKit: incoming calls done right.”

Need a second opinion on your iOS WebRTC stack?

We’ll read your ICE failure logs, your AVAudioSession config, and your SFU architecture in 30 minutes, and tell you exactly where the next bug will land.

Book a 30-min scoping call → WhatsApp → Email us →

What WebRTC actually is on iOS

WebRTC (Web Real-Time Communications) is an open IETF/W3C standard for sub-second peer-to-peer audio, video and data over UDP, with TCP fallback. On iOS it ships in two shapes. The first is a Swift/Objective-C framework built from the open-source Chromium WebRTC source tree (the “native” path). The second is RTCPeerConnection exposed inside Safari and WKWebView (the “web” path). For an iOS app that wants real-time calls, the native path comes out ahead on everything that counts here: hardware-accelerated H.264 encode/decode, CallKit interop, lower battery drain, and full control over the audio session.

If you’re new to the protocol, our primer What is WebRTC? walks through the building blocks. In short, WebRTC handles capture, encode, packetisation, congestion control, and encryption and decryption (DTLS-SRTP). It does not handle discovery (who calls whom), connection setup (the SDP/ICE handshake), or NAT traversal (STUN/TURN). You provide all three, and most tutorials skip that part.

A useful mental model: WebRTC is the engine. You still own the chassis (signaling), the wheels (STUN/TURN) and the dashboard (CallKit). On iOS you also own a small but treacherous part of the gearbox, AVAudioSession.

The five iOS-specific moving parts

Every shipped iOS WebRTC app contains five components. If your roadmap doesn’t name all five, it has a hole.

1. Signaling channel. A persistent connection to a server that exchanges SDP offers, answers, and ICE candidates between two devices that haven’t met. Most teams use WebSocket over TLS. Some use Firebase Realtime Database, Pusher, MQTT, or Socket.IO. Reliability and latency matter far more than the choice of protocol.

2. STUN server. Tells each peer its public IP address and port mapping so they can describe themselves to each other. Google’s public STUN (stun:stun.l.google.com:19302) is fine for prototypes; production deployments run their own.

3. TURN server. Relays media when the peers can’t reach each other directly. On iOS you can’t do without it. Cellular carrier NAT, corporate and hotel firewalls, and VPN or MDM profiles block direct UDP roughly 15–20% of the time in our production telemetry. Without TURN, one in five calls fails.

4. The WebRTC framework. The native iOS binary. You get it from the community-maintained Stasel fork (github.com/stasel/WebRTC) shipped through Swift Package Manager and CocoaPods, from a vendor SDK that wraps it (LiveKit, Daily, Stream, Agora), or by building it yourself from the Chromium source. Google stopped publishing official iOS binaries after M80 in 2020, so if a tutorial tells you to pod 'GoogleWebRTC', it’s out of date.

5. The iOS plumbing. CallKit (the native incoming-call UI), PushKit (VoIP push notifications that wake the app even from a terminated state), AVAudioSession (the route, category and mode), and the voip background mode in your Info.plist. Here iOS apps differ from web apps, and here most teams lose two weeks they didn’t plan for.

Five parts of an iOS WebRTC app: signaling, STUN, TURN, the WebRTC framework, and CallKit/PushKit/AVAudioSession plumbing

Figure 1. The five moving parts. WebRTC is the media engine; you still build and run the other four.

P2P vs SFU vs MCU on iOS

There are three architectures, each with a very different cost curve. Our deeper analysis lives in P2P vs MCU vs SFU for video conferencing; the short version is below.

Reach for P2P when: calls are 1-on-1 or up to 3 participants, you want zero server cost for media, and you can live with higher uplink usage on each device.

Reach for an SFU when: you need 4–100 participants, you want to record or stream the call, and you’re happy to pay for one mid-range server per ~500 concurrent media streams.

Reach for an MCU when: participants are on bandwidth-constrained 3G/4G networks and you can afford 5–10× the server CPU cost. In practice that usually means only telemedicine and broadcast scenarios.

1. P2P (peer-to-peer). Each iOS device sends N−1 streams (one per other participant) and receives N−1 streams. Above 3 callers, battery and uplink drain fast; an iPhone on LTE rarely sustains 4-way 720p P2P for more than 15 minutes. Use P2P for 1-on-1 telemedicine, dating and debate apps, and for any case where most calls are pairs.

2. SFU (Selective Forwarding Unit). Each device sends one upstream and receives N−1 downstreams from the SFU. The SFU forwards without decoding, so CPU stays low. mediasoup, LiveKit Server, Janus, Pion and Jitsi Videobridge are the open-source choices. This is the right default for any iOS app that needs more than 3 callers, group classes, or recording.

3. MCU (Multipoint Control Unit). The server decodes every upstream, mixes them into a single composed video, and sends one downstream per device. Devices receive one stream regardless of how many callers there are. The cost is steep: a single 50-person MCU call burns 4–8 dedicated CPU cores and adds 100–300 ms of mixing latency. In 2026 we use MCU only when an iOS device on a 3G fallback can’t sustain the SFU’s downlink.

P2P vs SFU vs MCU on iOS compared by participant count, iPhone uplink, server CPU, recording and typical use

Figure 2. P2P vs SFU vs MCU on iOS: green marks each architecture’s strong zone, orange its cost or hard limit.

Signaling: WebSocket, the bit nobody documents

Signaling is just a message bus, and its only job is to deliver SDPs and ICE candidates between callers reliably and quickly. WebSocket over TLS is the industry default: it’s connection-oriented and low-latency, and it fits naturally inside an iOS app that’s already authenticated against your backend.

A typical 1-on-1 message sequence: client connects to wss://signal.your.app with a JWT, joins a room, receives a list of peers, and exchanges offer, answer and ice-candidate messages with each peer. Use Trickle ICE so candidates start flowing as soon as setLocalDescription runs, in parallel with the offer/answer exchange. That shaves 200–800 ms off connection time.

Skeleton in Swift using Starscream:

import Starscream
import WebRTC

final class SignalingClient: WebSocketDelegate {
    private let socket: WebSocket
    weak var delegate: SignalingClientDelegate?

    init(url: URL, token: String) {
        var req = URLRequest(url: url)
        req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        socket = WebSocket(request: req)
        socket.delegate = self
    }

    func send(offer: RTCSessionDescription, to peerId: String) {
        let payload: [String: Any] = [
            "type": "offer",
            "to": peerId,
            "sdp": offer.sdp
        ]
        let data = try! JSONSerialization.data(withJSONObject: payload)
        socket.write(data: data)
    }
}

Teams usually get caught by three things here. The first is reconnect logic on flaky cellular: iOS will hand off between 5G, LTE and Wi-Fi mid-call, so your WebSocket needs exponential backoff and a server-side resume token. The second is authentication freshness, because JWT expiry during a long call drops new ICE candidates. Then there is ordering. If your transport doesn’t guarantee message order, ICE candidates can arrive before the SDP they describe and silently fail.

STUN and TURN — and why iOS needs both

STUN answers “what’s my public address?” TURN answers “the direct path is blocked, please relay for me.” On iOS specifically, three factors make TURN something you can’t skip.

1. Symmetric NAT on cellular. Major US, EU and APAC carriers run symmetric or port-restricted NAT on consumer LTE/5G plans. STUN tells you your address, but the address only works for the one server you spoke to, not for the peer trying to reach you. TURN relays around the asymmetry.

2. VPNs, MDM profiles and CGNAT. A managed device on a corporate VPN, or a carrier handing out carrier-grade NAT or IPv6-only addresses, routes media in ways that defeat direct peer paths. (iCloud Private Relay is a common myth here. It only proxies Safari and insecure web traffic and never touches your native app’s WebRTC UDP, so the cause is VPNs and CGNAT.) TURN over TLS on port 443 is the fallback that still gets through. Configure your TURN with both UDP and TLS transports and have the iOS client iterate through them in order.

3. Corporate Wi-Fi and hotel networks. These block UDP and non-443 outbound by default. TURN over TLS on 443, which effectively looks like HTTPS traffic, works in 99%+ of these environments.

For self-hosted TURN, coturn is the standard. A single dedicated-vCPU Hetzner CCX13 (€42.99/month for new orders since Hetzner’s 15 June 2026 repricing; a shared CPX22 at €19.49 is enough for a pilot) handles ~150 concurrent relay sessions at typical 720p bitrates. For managed TURN, the main options in November 2026 are Twilio Network Traversal Service, Cloudflare Realtime TURN, Xirsys and Metered. Prices vary a lot: Twilio charges $0.40 per GB in the US and Germany and up to $0.80 in Sydney and São Paulo, while Cloudflare charges $0.05 per GB of egress after the first 1,000 GB each month, an allowance shared with its Realtime SFU (Cloudflare pricing docs, November 2026). Relayed traffic is bidirectional, so the bill grows faster than most teams expect.

let iceServers = [
    RTCIceServer(urlStrings: ["stun:stun.your.app:3478"]),
    RTCIceServer(urlStrings: ["turn:turn.your.app:3478?transport=udp"],
                 username: ephemeralUsername,
                 credential: ephemeralPassword),
    RTCIceServer(urlStrings: ["turns:turn.your.app:443?transport=tcp"],
                 username: ephemeralUsername,
                 credential: ephemeralPassword)
]
let config = RTCConfiguration()
config.iceServers = iceServers
config.iceTransportPolicy = .all
config.bundlePolicy = .maxBundle
config.rtcpMuxPolicy = .require
config.continualGatheringPolicy = .gatherContinually

Have your backend sign short-lived TURN credentials per user, with a TTL at least as long as your longest call (a few hours is common): TURN servers such as coturn can check the expiry again on allocation refreshes and ICE restarts, so a two-minute credential risks dropping relayed calls mid-call. Fetch fresh credentials and apply them with setConfiguration(_:) before an ICE restart. Never embed long-lived static credentials in the iOS bundle: someone will extract and abuse them.

Stuck on ICE failures in production?

Send us a 5-minute webrtc-internals dump. We’ll come back with the exact NAT type, where TURN is dropping packets, and the one-line fix.

Book a 30-min triage call → WhatsApp → Email us →

The build-vs-buy decision

Framing the choice as “native WebRTC vs third-party SDK” sets up a false binary. In practice the spectrum has four points.

1. Pure native WebRTC + your own SFU + your own signaling. You get maximum control and the best cost discipline at scale, but it is the slowest path to MVP. Plan 8–14 weeks for a production-ready stack on iOS alone.

2. Native WebRTC + open-source SFU (mediasoup, LiveKit Server, Pion). You keep the same framework and skip writing the SFU, which gets you to MVP in 5–8 weeks. This is our default choice for clients planning to scale past 5M minutes/month, or 1–5M with in-house DevOps. Our WebRTC development team ships this setup on mediasoup or LiveKit with the iOS client built alongside it.

3. Cloud SDK (LiveKit Cloud, Daily, Stream, 100ms, Agora). The vendor supplies the iOS SDK, the SFU and a global edge, and MVP takes 1–3 weeks. Cost scales linearly with minutes. Lock-in is real but recoverable: LiveKit is open-source, so you can self-host the same code later.

4. Drop-in SDK with prebuilt UI (Daily Prebuilt, Whereby Embedded, Zoom Video SDK, Vonage). You reach MVP in days with almost zero engineering. The trade-off is that the vendor owns your UX and your unit economics.

Reach for a managed cloud SDK when: you need to ship in under three weeks, your 12-month volume stays under ~1M participant-minutes, and you’d rather rent the SLA than be the one fixing things at 3am.

Third-party SDK comparison

Below is pricing for the iOS-friendly SDKs we’ve shipped against, checked on each vendor’s pricing page in October 2026 (LiveKit and Agora re-checked in November 2026). Verify against the vendor’s public pricing page before you commit, because the numbers move quarterly, and run your own usage curve through them before drawing conclusions.

SDK Pricing model Free tier Pick when Watch out for
Agora $0.99/1K min audio, $3.99/1K HD, $8.99/1K Full HD video 10K min/mo Global reach (China especially), mature SDK Hard vendor lock-in; opinionated UI primitives
LiveKit Cloud Ship $50/mo incl. 150K min and 250 GB, then $0.0005/participant-min; Scale $500/mo incl. 1.5M min, then $0.0004; agents billed separately Build plan, ~5K min/mo Cost-sensitive scale, AI/agent workloads, OSS exit path Data transfer (250 GB on Ship, 3 TB on Scale) and agent minutes dominate real bills
Daily.co Per-participant-minute, custom enterprise tiers Yes, Prebuilt UI Fastest MVP; Daily Prebuilt cuts UI to zero No self-host path; opaque enterprise pricing
Stream Video Usage-based per 1K participant-min; first $100/mo of usage free; Enterprise from 1M min $100 monthly credit Need chat + calls in one SDK; SOC 2 Complex pricing math; recording + storage extra
100ms ~$0.004/participant-min HD video, ~$0.001/min audio 10K min/mo Balanced cost/features, strong mobile SDKs Smaller global PoP footprint than Agora
Vonage Video $0.0041/participant-min standard; up to 25 active publishers per session 100K trial minutes Need built-in broadcast/HLS; legacy Tokbox migration Slower roadmap; older API surface
Self-hosted SFU (mediasoup/LiveKit OSS) on Hetzner €20–140/mo per server at Hetzner’s June 2026 prices + ops time N/A — OSS >1–5M min/mo; HIPAA/data-residency; full control Needs DevOps; you own the SLA at 3am

Two notes from real bills. Ignore any 2024 tutorial that calls Twilio Programmable Video “dead.” Twilio announced a December 2024 end-of-life in late 2023, pushed it to December 2026 in March 2024, then reversed course in October 2024 and kept Video a standalone, actively-supported product. It is a valid option again, and Twilio keeps adding features: on 30 September 2026 Twilio put a Video Media SDK for Node.js into public beta, which lets a server join a Group Room as a participant and read or publish decoded frames, for example to run transcription next to an iOS call (Twilio changelog, 2026). We mapped the paths in our Twilio Video migration guide. With Agora, the headline rate is easy to misread: “participant minutes” meter every joiner, every minute. A 10-person, 60-minute call is 600 minutes of billing, not 60. Our deeper teardown is in Agora.io alternatives and WebRTC vs Agora architecture trade-offs.

Integrating the WebRTC framework the modern way

In old WebRTC iOS tutorials, the dependency line is usually the most outdated part. Google retired its official iOS binary distribution after Chromium milestone M80. The community-maintained replacement is Stasel’s WebRTC fork, which ships pre-built XCFrameworks for every Chromium milestone via SPM and CocoaPods. As of November 2026 the latest release is M157 (5 November 2026), and Stasel now ships a new milestone every two to four weeks (M151 to M157 arrived between late August and early November). Releases since M152 also include dSYM files, so crashes inside the framework symbolicate in your crash reporter. The binary supports iOS 15+, macOS 12+ and Mac Catalyst. Pin a milestone and don’t let the version float.

Swift Package Manager (recommended in 2026). In Xcode, File → Add Packages, paste https://github.com/stasel/WebRTC and pin the version (e.g. 157.0.0). Floating latest invites trouble.

CocoaPods. Add to your Podfile:

target 'YourApp' do
  use_frameworks!
  pod 'WebRTC-lib', '157.0.0'
end

Manual build from source. Only do this if you need a patched build, e.g. SFrame E2EE support that hasn’t landed upstream, or a custom audio processing module. Plan three engineering days. The Chromium depot_tools + gn gen + ninja process is well documented, but small mistakes cost a lot of time.

Required Info.plist entries you’ll forget at least once:

<key>NSCameraUsageDescription</key>
<string>Camera access is required for video calls.</string>
<key>NSMicrophoneUsageDescription</key>
<string>Microphone access is required for calls.</string>
<key>UIBackgroundModes</key>
<array>
  <string>audio</string>
  <string>voip</string>
</array>

Add the Push Notifications and Background Modes capabilities in the Signing & Capabilities tab and you’re ready to wire the call flow.

The 1-on-1 call flow in Swift

The call sequence is the same on every WebRTC platform. The Swift below is condensed but keeps a production structure. We left out error handling and threading to keep it readable; both still matter in a real app.

1. Create a peer connection factory once. Reuse it for the lifetime of the app.

RTCInitializeSSL()
let encoderFactory = RTCDefaultVideoEncoderFactory()
let decoderFactory = RTCDefaultVideoDecoderFactory()
let factory = RTCPeerConnectionFactory(
    encoderFactory: encoderFactory,
    decoderFactory: decoderFactory
)

2. Capture local audio and video.

let audioSource = factory.audioSource(with: nil)
let audioTrack = factory.audioTrack(with: audioSource, trackId: "audio0")

let videoSource = factory.videoSource()
let videoCapturer = RTCCameraVideoCapturer(delegate: videoSource)
let frontCamera = RTCCameraVideoCapturer.captureDevices()
    .first { $0.position == .front }!
let format = RTCCameraVideoCapturer.supportedFormats(for: frontCamera)
    .first { CMVideoFormatDescriptionGetDimensions($0.formatDescription).width == 1280 }!
videoCapturer.startCapture(with: frontCamera, format: format, fps: 30)
let videoTrack = factory.videoTrack(with: videoSource, trackId: "video0")

3. Build the peer connection. Configure ICE servers, attach the local tracks.

let pc = factory.peerConnection(
    with: config,
    constraints: RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil),
    delegate: self
)!
pc.add(audioTrack, streamIds: ["stream0"])
pc.add(videoTrack, streamIds: ["stream0"])

4. Create offer / answer / set remote description. Trickle ICE candidates as they arrive.

// Caller
pc.offer(for: mediaConstraints) { sdp, error in
    guard let sdp = sdp else { return }
    pc.setLocalDescription(sdp) { _ in
        signaling.send(offer: sdp, to: peerId)
    }
}

// Callee, on receiving an offer
pc.setRemoteDescription(remoteSdp) { _ in
    pc.answer(for: mediaConstraints) { sdp, error in
        guard let sdp = sdp else { return }
        pc.setLocalDescription(sdp) { _ in
            signaling.send(answer: sdp, to: peerId)
        }
    }
}

// Both sides, on each new local candidate
func peerConnection(_ pc: RTCPeerConnection, didGenerate candidate: RTCIceCandidate) {
    signaling.send(candidate: candidate, to: peerId)
}

// On each remote candidate
pc.add(remoteCandidate)

5. Render remote video. Use RTCMTLVideoView, which is Metal-backed and hardware-accelerated. Don’t use RTCEAGLVideoView; OpenGL ES is deprecated on iOS.

func peerConnection(_ pc: RTCPeerConnection,
                    didAdd rtpReceiver: RTCRtpReceiver,
                    streams: [RTCMediaStream]) {
    guard let remoteVideoTrack = rtpReceiver.track as? RTCVideoTrack else { return }
    DispatchQueue.main.async {
        let view = RTCMTLVideoView(frame: self.remoteContainer.bounds)
        view.videoContentMode = .scaleAspectFill
        self.remoteContainer.addSubview(view)
        remoteVideoTrack.add(view)
    }
}

6. Rendering in SwiftUI. WebRTC has no SwiftUI-native renderer. Wrap RTCMTLVideoView in a UIViewRepresentable and detach it from the track when SwiftUI tears the view down, or frames keep flowing into a dead view. Give it .id(track.trackId) so a new remote track builds a new renderer.

import SwiftUI
import WebRTC

struct RemoteVideoView: UIViewRepresentable {
    let track: RTCVideoTrack

    func makeCoordinator() -> RTCVideoTrack { track }

    func makeUIView(context: Context) -> RTCMTLVideoView {
        let view = RTCMTLVideoView()
        view.videoContentMode = .scaleAspectFill
        track.add(view)
        return view
    }

    func updateUIView(_ view: RTCMTLVideoView, context: Context) {}

    static func dismantleUIView(_ view: RTCMTLVideoView,
                                coordinator: RTCVideoTrack) {
        coordinator.remove(view)
    }
}

Want a runnable WebRTC iOS example first? Stasel’s demo app (github.com/stasel/WebRTC-iOS) is the reference 1-on-1 project: a Swift client on the same package plus a small signaling server. Get two devices talking there, then move the code into your app and add CallKit.

CallKit + PushKit: incoming calls done right

If users have to keep the app open to receive calls, the app fails at its main job. The combination of PushKit (to wake the device) and CallKit (to show the native incoming-call UI) makes a WebRTC iOS app feel like FaceTime instead of like Zoom-on-launch. Apple is also strict here: since iOS 13, every PushKit VoIP push that hits the device must result in a CallKit reportNewIncomingCall call within seconds, or iOS will throttle and eventually disable VoIP push for your app. The iOS 26 SDK removed the last exception: an app built against it that receives a VoIP push and does not report a call to CallKit (or LiveCommunicationKit) is terminated, and development and TestFlight builds now show a warning alert when it happens (Apple Developer Forums, 2025). Since 28 April 2026 App Store Connect accepts only builds made with Xcode 26 and an iOS 26 SDK, so the rule now covers new apps and every update you ship (Apple developer news, 2026).

One regional caveat. CallKit is not available to apps on the China mainland App Store; Apple began pulling CallKit apps there in 2018 under local regulations. If you ship in China, put CallKit behind a region flag and fall back to a regular notification plus an in-app ringing screen.

Pick the CXHandle type carefully as well. On iOS 26, calls reported with a .generic handle still get separate rows in Phone Recents, but the details screen of any row lists every call from your app. Apple DTS reproduced this in its Speakerbox sample in June 2026 and said the change may not be intentional. Handles of type .phoneNumber and .emailAddress still keep each contact’s call history separate. If per-contact history matters, report .phoneNumber or .emailAddress when you have a stable identifier; otherwise keep .generic, or set includesCallsInRecents = false on your CXProviderConfiguration.

1. Register for VoIP push.

import PushKit

final class VoIPRegistrar: NSObject, PKPushRegistryDelegate {
    let registry = PKPushRegistry(queue: .main)
    func start() {
        registry.delegate = self
        registry.desiredPushTypes = [.voIP]
    }
    func pushRegistry(_ registry: PKPushRegistry,
                      didUpdate pushCredentials: PKPushCredentials,
                      for type: PKPushType) {
        let token = pushCredentials.token.map { String(format: "%02x", $0) }.joined()
        backend.uploadVoIPToken(token)
    }
}

2. Backend sends a VoIP push. The APNs topic is your.bundle.id.voip, with priority 10 and push type voip. The payload carries the caller name, room ID and a fresh signaling token.

3. App receives the push and reports the call to CallKit immediately.

import CallKit

func pushRegistry(_ registry: PKPushRegistry,
                  didReceiveIncomingPushWith payload: PKPushPayload,
                  for type: PKPushType,
                  completion: @escaping () -> Void) {
    let info = payload.dictionaryPayload
    let update = CXCallUpdate()
    update.remoteHandle = CXHandle(type: .generic, value: info["caller"] as? String ?? "")
    update.hasVideo = true
    let uuid = UUID()
    provider.reportNewIncomingCall(with: uuid, update: update) { error in
        if error == nil {
            self.callManager.prepareIncoming(uuid: uuid, info: info)
        }
        completion()
    }
}

4. CXProviderDelegate handles answer/decline. When the user taps Answer, configure the audio session, build the peer connection and complete the SDP handshake. Don’t do any of that in didReceiveIncomingPushWith: CallKit hasn’t taken control of the audio session yet, and AVAudioSession will fight you.

iOS incoming-call flow: APNs VoIP push, reportNewIncomingCall, CallKit UI, then didActivate before starting WebRTC media

Figure 3. The incoming-call flow. The two orange traps mark where VoIP push gets throttled or the first seconds of audio go silent.

AVAudioSession traps

More iOS WebRTC bugs trace back to AVAudioSession than to the WebRTC framework itself. We stick to three rules.

1. Use .playAndRecord with mode .voiceChat. This turns on Apple’s built-in echo cancellation and noise suppression. Enabling the WebRTC software AEC on top of it processes the audio twice and produces the metallic robot voice everybody complains about.

2. Let CallKit own activation. When the user taps Answer in the CallKit UI, CallKit raises the audio session itself. Calling setActive(true) from your code at the wrong moment causes a route mismatch that mutes outgoing audio, so wait for provider(_:didActivate:) before starting media. On the WebRTC side, set RTCAudioSession.sharedInstance().useManualAudio = true at launch, then in didActivate call audioSessionDidActivate(_:) and set isAudioEnabled = true. If you skip this, the call connects with no audio.

3. Handle interruptions. An incoming GSM call, Siri or another VoIP app can interrupt your session. Subscribe to AVAudioSession.interruptionNotification, mute your RTCAudioTrack on .began and restore on .ended. Test the GSM-call interruption explicitly, since it causes the most common “the call goes silent forever” bug.

H.264, simulcast and Apple Silicon

iOS’s native WebRTC framework hardware-accelerates one video codec: H.264 (Constrained Baseline and High), through VideoToolbox. The Stasel build also carries VP8, VP9 and AV1, but only in software, so they work at a higher cost in CPU and battery. HEVC support is a common misconception. As of M157 (November 2026) the SDP negotiation and RTP packetisation for H.265 are compiled in, but WebRTC ships no HEVC encoder or decoder for Apple platforms, so do not plan an H.265 call path on the stock framework. Opus handles audio. If you are new to codecs, our primer on digital video and codecs is the fastest way in. The codec set matters for two reasons.

Cross-codec interoperability. If your other clients are browsers, keep in mind that Chrome and Firefox prefer VP8 by default. iOS will decode VP8, but in software, so a busy grid of VP8 tiles heats the phone and drains the battery. Put H.264 (hardware on both ends) first in your SFU’s codec preferences, keep VP8 and VP9 as fallbacks, check codec support with factory.rtpSenderCapabilities(forKind: "video") at startup, then confirm the negotiated codec from the codec entry in RTCStatsReport.

Simulcast restrictions. iOS publishes H.264 simulcast with up to three resolution layers, each from its own VideoToolbox encoder, so SFU layouts built on three rungs per peer work fine. iOS has no hardware SVC: the VideoToolbox H.264 encoder does not produce temporal layers, and VP9 or AV1 SVC (for example L3T3) runs in software. For iPhones, prefer simulcast over SVC in your SFU; mediasoup, LiveKit Server and Janus all support that split.

Apple Silicon and the A17 Pro+ media engine. On A17 Pro and newer (A18, A19), hardware H.264 encode/decode costs almost nothing in CPU. A 1080p30 publisher on these devices takes ~3% CPU. On older devices (A12 and earlier) the same publisher takes 12–18%, and battery and thermal limits will cut the frame rate after 10–15 minutes. Unless you’ve measured, cap publish resolution at 720p on devices older than A14.

Security and compliance

Every WebRTC connection is encrypted by default. DTLS-SRTP is mandatory in the spec, and you can’t turn it off. That gives you hop-by-hop confidentiality and integrity. It does not give you end-to-end encryption when an SFU is in the path, because the SFU terminates the DTLS session. Our deeper write-up is in WebRTC security in plain language.

1. End-to-end encryption. If the threat model includes the SFU operator, layer SFrame on top of SRTP. SFrame encrypts the payload with a key the server doesn’t hold, so the SFU still routes packets but can’t decode media. The encryption runs in the clients: LiveKit’s client SDKs ship end-to-end encryption, and an SFU such as mediasoup forwards the encrypted frames untouched. The stock stasel/WebRTC binary exposes no frame-encryption API, so on iOS use LiveKit’s Swift SDK or a custom WebRTC build.

2. HIPAA. You need a signed BAA with every infrastructure vendor that touches PHI, audit logs of who joined which call and when, recording controls (consent, retention, encryption at rest) and access controls on the signaling server. We covered the full playbook in building a HIPAA-compliant video platform. CirrusMED and Cloud Doctors run on this same pattern.

3. GDPR. You need a lawful basis (usually consent) before recording, data residency (your SFU and recording storage must live in the right region), a DPIA for high-risk processing, and a “delete my data” flow that actually propagates through recordings, transcripts and logs.

4. SOC 2 Type II. Here the choice of SDK or self-hosted stack makes a big difference. LiveKit Cloud, Stream and Daily are SOC 2 Type II out of the box. If you roll your own, expect a 12-month audit and a serious conversation with a CISO.

Cost model: self-hosted SFU vs Agora vs LiveKit

Below are worked examples for three usage tiers, assuming HD video group calls and 720p publishers. We round generously and leave out CDN and recording costs to keep the numbers simple.

Monthly volume Self-hosted SFU on Hetzner LiveKit Cloud Agora HD
100K participant-min ~$125/mo (one CCX23 + CPX22 TURN) ~$50/mo (~$155 with data transfer) ~$400/mo
1M participant-min ~$375/mo (2× CCX33 + CCX13 TURN) ~$475/mo (~$1,300 with data transfer) ~$4,000/mo
10M participant-min ~$2,500–4,000/mo (cluster + bandwidth) ~$3,900/mo (~$14,800 with data transfer) ~$40,000/mo

The self-hosted column uses Hetzner’s prices for new orders since 15 June 2026, when dedicated-vCPU CCX instances rose 2.2–2.7× (a CCX33 went from €62.49 to €138.49 a month, per Hetzner’s price-adjustment notice). Servers ordered before that date keep their old price. Agora is $3.99 per 1,000 HD minutes. For LiveKit Cloud we take the cheaper of Ship or Scale for participant-minutes only; downstream data beyond the plan allowance is billed on top (Ship: 250 GB included, then $0.12 per GB; Scale: 3 TB, then $0.10 per GB, per LiveKit’s pricing page in November 2026). At 720p that downstream traffic usually outweighs the minutes: at ~1.5 Mbps per subscriber a participant-minute moves about 11 MB, so 1M minutes is ~11 TB and 10M minutes ~110 TB. The estimates in brackets in the LiveKit column add that data transfer. The table leaves out two things. The self-hosted column hides one DevOps engineer’s ongoing cost: figure $4–8K/month at 20% time once it’s stable. The LiveKit / Agora columns hide the integration speed-up. You ship two months earlier, and in the first year that is often worth more than the cloud premium.

Our infrastructure post on AWS vs DigitalOcean vs Hetzner walks through the bandwidth math. Bandwidth is the reason Hetzner is the right SFU host most of the time and AWS is the wrong one.

Monthly media cost: self-hosted SFU (Hetzner, June 2026) vs LiveKit Cloud vs Agora at 100K, 1M, 10M minutes

Figure 4. Monthly media cost at three usage tiers. Each panel is scaled to its own max, so every bar stays readable. LiveKit bars show participant-minutes only; data transfer comes on top (see the table).

Burning money on Agora minutes?

We’ve migrated three production iOS apps off Agora to self-hosted mediasoup or LiveKit OSS — with no UX regression. Send us your bill and your call topology.

Book a 30-min cost-cut call → WhatsApp → Email us →

Mini case: shipping a telemedicine iOS call flow in 12 weeks

Situation. A US private-practice telemedicine startup came to us with a working web flow and an Android client mid-build, but no iOS app. The investor demo was 12 weeks out. They needed HIPAA-compliant video and a CallKit incoming-call experience, plus the ability to record consultations to encrypted storage with patient consent.

Plan. In weeks 1–3 we wired the Stasel WebRTC SPM dependency, built the signaling layer on the existing Node WebSocket gateway and stood up coturn on Hetzner with TURN over TLS on 443. Weeks 4–7 went to the CallKit + PushKit + AVAudioSession integration, which is the part that ate the schedule. In week 8 we added an SFU on mediasoup for the planned three-way doctor + patient + interpreter flow. Weeks 9–11 covered recording-to-S3 with at-rest AES-256 and a signed BAA in place. Week 12 was App Store review and the demo.

Outcome. First-call success rate was 98.3% across the first 1,200 production calls. Median connect time was 1.4 seconds for direct P2P and 2.1 seconds for TURN-relayed calls (~14% of calls). The investor demo closed the next round. We used the same pattern for CirrusMED and Cloud Doctors; the deliverables are in our telemedicine features playbook.

A decision framework — pick your iOS WebRTC stack in five questions

1. How many simultaneous video participants in a typical call? With 1–3, P2P is an option and a €20–45/month TURN server is enough. With 4–100 you need an SFU. At 100+ you need SFU + recording + selective forwarding logic, and the right answer is almost always “use a managed SFU vendor for v1.”

2. What’s your projected monthly minute volume in 12 months? Below 1M minutes, ship on a cloud SDK and revisit later. At 1–5M minutes a cloud SDK still wins on total cost of ownership unless you have a dedicated DevOps team. Above 5M, self-host on mediasoup or LiveKit OSS.

3. Do you need HIPAA, GDPR data residency, or air-gapped on-prem? If any of these apply, third-party cloud SDKs narrow to LiveKit Cloud (signed BAA available) or Stream (HIPAA as an Enterprise add-on). Otherwise, self-host. We’ve built air-gapped on-prem WebRTC for Nucleus, and it is a very different kind of project.

4. How quickly do you need to ship? Two weeks: Daily Prebuilt or Vonage embedded. Six weeks: native + LiveKit Cloud. Twelve weeks: native + self-hosted mediasoup. Anything faster than two weeks means a Daily Prebuilt webview wrapped in a native shell.

5. What’s your team’s WebRTC experience? If it’s zero, pick a managed SDK. With one past project behind you, an open-source SFU plus native WebRTC is within reach. Teams that have shipped two or more products can self-host with confidence. An inexperienced team self-hosting in production usually pays for it with a weekend outage nobody forgets.

Five pitfalls we keep seeing in iOS WebRTC code reviews

1. Embedding static TURN credentials in the iOS bundle. Anyone who pulls your IPA gets free relay. Issue short-lived, per-user credentials signed by your backend, with a TTL that covers your longest call. Writing those 60 lines of backend code is far easier than cleaning up after an abuse incident.

2. Calling setActive(true) on AVAudioSession from your own code during CallKit-led calls. CallKit activates the session itself. If you do it first, the microphone stays muted for the first few seconds and sometimes for the whole call. Wait for provider(_:didActivate:).

3. Not reporting every VoIP push to CallKit. Apple throttles VoIP push for apps that receive a push and don’t immediately call reportNewIncomingCall. Since the iOS 26 SDK the penalty goes beyond throttling: the system terminates the app. If the call has already ended by the time the push arrives, report it anyway and end it right away; otherwise the app is terminated and VoIP pushes get throttled. Every App Store upload has required the iOS 26 SDK since 28 April 2026, so there is no older-SDK grace period left.

4. Defaulting to VP8 on iOS and paying for it in battery. iOS decodes VP8 and VP9 only in software. A VP8-first SFU leaves iPhones hot and draining while the H.264 hardware sits idle. Put H.264 first in your codec preferences and keep VP8 as a fallback.

5. Using RTCEAGLVideoView in 2026. OpenGL ES is deprecated. RTCMTLVideoView is the Metal-backed renderer: it’s faster, uses less power, and it’s the renderer to use now that OpenGL ES is deprecated.

KPIs: what to measure on every iOS WebRTC call

1. Quality KPIs. Median round-trip time below 200 ms, packet loss below 2%, jitter below 30 ms, video freeze count below 1 per minute, MOS audio score above 4.0. Pull these from RTCStatsReport every 5 seconds and ship them to your APM. On iOS, a value outside the band usually points to a TURN issue or an AVAudioSession route problem, and the two need different fixes.

2. Business KPIs. Call setup time (offer→ICE-connected) below 2.0 s on cellular, first-call success rate above 95%, mid-call drop rate below 1.5%, and daily active call rate per DAU. The first three correlate strongly with retention. In one case, cutting setup time by 800 ms on slower cellular networks gave us a 0.4 percentage point improvement in week-one retention.

3. Reliability KPIs. SFU uptime 99.95%+, signaling reconnection success rate above 99% (we measure it across 5G↔LTE↔Wi-Fi handoffs), CallKit-throttle rate at zero, and a hard cap on AVAudioSession deactivation errors that pages us when crossed. Our deeper test playbook is how to test a WebRTC stream.

When NOT to build native iOS WebRTC

If your call is “watch a presenter, occasionally raise hand” with thousands of viewers, use HLS or LL-HLS for the broadcast and keep WebRTC for the speakers only. We’ve covered the cut-over in WebRTC video streaming vs HLS and the scaling story in scale video streaming to 1M viewers.

If your iOS app is a thin native wrapper around an existing, well-tested web flow and your investor demo is in three weeks, do not rebuild on native WebRTC. Wrap Daily Prebuilt or LiveKit’s React Native SDK, ship the demo and replace it later. In every product we’ve seen, speed to market mattered more than architectural purity for the first six months.

If your calls have >500 simultaneous participants and you’re thinking of writing your own SFU, stop. Cascading SFUs, geographic routing, replica strategy and recording fan-out add up to a 12-month project for a senior team. Use LiveKit Cloud or Agora until you have the engineering bandwidth to bring it in-house.

FAQ

Does iOS support WebRTC natively?

Yes. Safari and WKWebView (iOS 14.3+) expose RTCPeerConnection through WebKit, and the open-source WebRTC framework ships as a native iOS binary you can import via Swift Package Manager or CocoaPods. For a real iOS app you almost always want the native framework over the WebView path. It gives you CallKit, hardware H.264 and a proper audio session.

Do you really need a TURN server?

For any production iOS app, yes. In our telemetry roughly 15–20% of calls need relayed media because of cellular carrier NAT, VPN or MDM profiles, or corporate firewalls. Without TURN those calls fail silently at the ICE-connected step. coturn on one Hetzner CCX13 (€42.99/month at June 2026 prices) handles ~150 concurrent relays; Cloudflare Realtime TURN at $0.05 per GB is the cheapest managed option.

Can you use WebRTC inside a WKWebView instead of the native framework?

Technically yes, since iOS 14.3. In practice you lose CallKit interop and tight AVAudioSession control, and battery life is worse than with the native framework. Use WKWebView only for very short MVP horizons or when you need strict parity with browser features, and plan to migrate later.

How do you add CallKit to a WebRTC iOS app?

Register a CXProvider, request .voIP push tokens, and on every incoming VoIP push call reportNewIncomingCall within seconds. Then implement CXProviderDelegate. Start media in didActivate audioSession and no earlier. If you skip this, VoIP push gets throttled, and apps built with the iOS 26 SDK are terminated.

Is WebRTC secure enough for telemedicine?

DTLS-SRTP is mandatory and gives you confidentiality and integrity. For HIPAA and similar regimes you also need a signed BAA with every infrastructure vendor, encrypted-at-rest recordings, audit logs and granular access control on the signaling server. Stricter threat models add SFrame end-to-end encryption so the SFU can’t see media. We documented the full stack in our HIPAA-compliant video platform guide.

Is it cheaper to build with native WebRTC or use Agora/LiveKit?

Below ~1M participant-minutes/month, a cloud SDK is almost always cheaper once you count engineering time and on-call cost. Above ~5M minutes/month, a self-hosted SFU on Hetzner pays for itself within months compared with Agora. Against LiveKit Cloud the minutes alone look close since Hetzner’s June 2026 repricing, but once LiveKit’s data-transfer charges for 720p video are counted, self-hosting still wins clearly from about 1M minutes a month. In the 1–5M middle band the choice depends on team experience and how much you value control over the SLA.

Why does the audio sound robotic or echoed in my iOS WebRTC app?

It’s almost always a double AEC: WebRTC’s software echo cancellation running on top of Apple’s hardware AEC. Set the AVAudioSession to .playAndRecord with mode .voiceChat, which turns on Apple’s AEC, and disable WebRTC’s software AEC. That removes the robot voice.

How long does it take to ship a production iOS WebRTC app?

For a 1-on-1 video flow with CallKit, signaling, TURN and recording, a senior iOS team familiar with WebRTC needs 8–12 weeks. Add 2–4 weeks for HIPAA/GDPR compliance work and another 2 weeks for SFU integration if you need group calls. We’ve cut the schedule to 6–8 weeks with LiveKit Cloud, and to 2–3 weeks with Daily Prebuilt for an MVP.

Which video codecs does WebRTC support on iOS?

H.264 is the only hardware-accelerated video codec in the native iOS WebRTC framework. VP8, VP9 and AV1 run in software, and as of M157 (November 2026) WebRTC ships no HEVC encoder or decoder for Apple platforms. Audio uses Opus.

What is stasel/WebRTC?

It’s the community-maintained distribution of Google’s WebRTC framework for Apple platforms: pre-built XCFrameworks for every Chromium milestone, installed through Swift Package Manager or CocoaPods (pod WebRTC-lib). Google stopped shipping official iOS binaries after M80, which makes it the default native dependency in 2026. The latest release is M157 (5 November 2026).

What is the best WebRTC SDK for iOS?

That depends on volume and how much control you need. For a self-built stack we start with stasel/WebRTC (M157, via Swift Package Manager or CocoaPods). For a managed SDK under ~1M participant-minutes a month we default to LiveKit, because its server is open source and you can self-host later. Agora fits when you need reach in China, Daily Prebuilt gives the fastest MVP, and Stream covers chat and calls in one SDK.

Does WebRTC work on iPad and Mac?

Yes. The same XCFramework covers iOS and iPadOS 15+, macOS 12+ and Mac Catalyst, so one Swift code base serves iPhone, iPad and Mac. On iPad, Split View or Stage Manager can interrupt camera capture, so check AVCaptureSession’s isMultitaskingCameraAccessSupported (iPadOS 16+) and handle the interruption in your UI.

What changed for VoIP push and CallKit in iOS 26?

Apps built with the iOS 26 SDK are terminated if they receive a PushKit VoIP push and don’t report a call to CallKit or LiveCommunicationKit. The last exemption entitlement no longer works. Development and TestFlight builds also show a diagnostic alert when VoIP push reporting fails, so you see the bug before review. Since 28 April 2026 every App Store upload must be built with Xcode 26, which means the rule applies to every app you can still update.

How do you use WebRTC in Swift?

Add stasel/WebRTC through Swift Package Manager (pin 157.0.0) and create one RTCPeerConnectionFactory. Capture with RTCCameraVideoCapturer, exchange the SDP offer, answer and ICE candidates over your WebSocket, then render the remote track in RTCMTLVideoView, wrapped in UIViewRepresentable for SwiftUI. If you’d rather use a ready-made Swift video calling component, the LiveKit, Stream and Agora iOS SDKs wrap the same steps in prebuilt views.

Where can I find a WebRTC iOS example project?

Start with stasel/WebRTC-iOS on GitHub. It’s a 1-on-1 Swift client built on the stasel/WebRTC package, with a small signaling server. The Swift snippets in this guide follow the same flow and add the parts the demo leaves out: ephemeral TURN credentials, SwiftUI rendering, CallKit and PushKit.

Architecture

P2P vs MCU vs SFU for Video Conference Apps

Decision tree, CPU/bandwidth math, and when each architecture earns its keep.

Security

WebRTC Security in Plain Language

DTLS-SRTP, SFrame for E2EE, and how to handle keys you don’t want to lose.

Compliance

HIPAA-Compliant Video Platform Playbook

BAAs, audit logs, recordings, and the architectural shape we use for telemedicine.

Cost

Agora.io Alternatives Compared

Pricing math, migration paths, and the SDKs that consistently come out cheaper.

Testing

How to Test a WebRTC Stream

From RTCStatsReport to synthetic load — what to measure and how to alert on it.

Ready to ship video calls iOS users will actually keep open?

WebRTC on iOS is a solved problem once you accept that it’s really five problems stitched together. Choose the architecture (P2P, SFU, MCU) by participant count and the build-vs-buy point by minute volume and time-to-market. Budget two engineering weeks for CallKit + PushKit + AVAudioSession whichever path you take. Prefer H.264, issue ephemeral TURN credentials, and from day one measure what correlates with retention: setup time, first-call success and mid-call drops.

If you want a faster route, our video chat app development team builds iOS calling apps on WebRTC with CallKit, TURN and recording in the scope. Send us your topology, your usage projection and (if you have one) your current Agora bill. We’ll come back with a stack you can ship in 6–12 weeks and a cost curve that doesn’t double as you grow. This is the kind of work behind 20 years of video software at Fora Soft.

Book cover: Video Streaming, Volume 3 of the Fora Soft Video Engineering Handbook

The book · Volume 3 of 7

Video Streaming: A Complete Guide to Video Delivery: From ABR and CDNs to Players, WebRTC, DRM, and the Economics of Streaming

With CallKit, signaling and TURN in place, quality on a real network becomes the job. Volume 3 covers WebRTC and real-time delivery alongside ABR, players, QoE monitoring and the economics of streaming, which is where the self-hosted SFU versus SDK math gets settled. Written by Nikolay Sapunov, CEO at Fora Soft.

Read it on Amazon →Kindle & paperback · Fora Soft Video Engineering Handbook

Talk to a senior iOS WebRTC engineer this week

30 minutes, no slides — just your stack, our notes, and the next three things to fix or build.

Book a 30-min call → WhatsApp → Email us →

  • Development