Making an iPhone Call Through a SIM Card That Isn't in the iPhone (6)
Previous: On a Mac | Next: An Android Tablet Drives It Directly | 中文版:iPhone 客户端
What the earlier posts produced is a Raspberry Pi gateway: a few SIM cards plugged into it, able to send and receive SMS, make calls, and even reach the carrier’s core network over Wi-Fi.
But it is a box sitting in a corner. What I actually wanted was a few extra lines on my phone that work just like the phone’s own number: a full-screen incoming-call UI, answering from the lock screen, SMS as the familiar bubble conversations, and the system keypad for typing IVR extensions while dialing.
The iPhone has no USB host capability, so it can neither plug in nor drive the modem. That makes this app a client of the gateway. The UI has four tabs (Phone, Messages, Recordings, Settings) and a line picker in the navigation bar.
No WebRTC, and no SIP client either
The first instinct might be to implement a SIP client on the phone, or to bring in WebRTC. Neither is necessary: the gateway has already done the hard part, and the phone only needs to speak HTTPS.
| The phone needs | The gateway provides |
|---|---|
| A list of lines | GET /api/lines: ID, name, number, signal, whether it can dial, the call in progress. All served from cache, so refresh as often as you like on returning to the foreground without costing the modem a single AT command |
| Events for every line | GET /api/events: one SSE stream carrying call-state changes and new SMS, each tagged with its line, plus heartbeats |
| Call audio | A bidirectional WebSocket, binary frames, 8 kHz mono 16-bit |
| Recordings | A list, plus downloads that support resuming |
| Incoming calls in the background | VoIP push |
All of these endpoints are written up in a single OpenAPI description (72 paths). The frame format of the voice WebSocket, in particular, used to be known only to its own handler function. If an interface’s format exists only in the code, it isn’t really an interface yet.
Calls go through CallKit rather than a UI the app draws itself. CallKit is the system framework iOS provides for third-party calling apps, and the benefits are very concrete: the incoming-call screen can appear on the lock screen, the call carries on after you leave the app, and DTMF tones come from the system keypad (which is what makes automated voice menus usable).
On the audio side, the app converts between 8 kHz and the phone hardware’s 48 kHz and keeps a 60 ms jitter buffer. Why a buffer at all: the audio travels over TCP and arrives in bursts, while the speaker drains it at a steady rate, so without a buffer every gap between bursts becomes a hole in the sound. But the buffer also has to be shallow, because every millisecond of delay added here is heard directly as call latency.
Setting it up
cd ios/VoHivePhone
xcodegen generate # the project is generated from config; never edit the project file by hand
open VoHivePhone.xcodeproj # pick a development team, run on a real device
On first launch, enter the gateway address in Settings. The field accepts anything a human might type (192.168.1.20:7575, a hostname, a full URL) and fills in the rest automatically.
The gateway address is the “root” of the whole app: changing it means logging in again, discarding the old gateway’s cache, and reconnecting the event stream. Places like this, where “changing one setting has to drag five other things along with it,” are best gotten right in one go; otherwise they leave behind all kinds of invisible leftover state.
Two holes to plug in the gateway first
To support a phone that stays connected all the time, the gateway first needed two fixes.
Right after the service starts, nobody notices incoming calls
Cause: the modem’s incoming-call callback belongs to a control object, and that object is only created when some client actively queries call status. On a freshly started service there is no callback at all, and an incoming call goes unnoticed until someone comes asking.
That was never a problem in the web-console era: a person opens the page and polling begins. But a phone that keeps an event stream open all the time can’t rely on “someone coming asking.”
Fix: install an event monitor for every device at startup, adjusting automatically as devices come and go.
Two consumers, each seeing half the events
Cause: events went through a shared channel, and the handset bridge was already reading from it. Two readers each got roughly half of the state changes.
This is exactly the same trap as the “voice loses half its audio” bug from part 3: a Go channel delivers each value to only one receiver. The same bug has shown up three times in this project, in a different form each time.
Fix: switch to a subscription model, with an independent channel per consumer. Delivery is lossy: the send happens on the modem’s notification path and must never be blocked by a slow reader.
Verification: send an SMS from a mainland China SIM to another line on the gateway; it arrives over the Wi-Fi calling path and comes out of the event stream:
{"type":"sms.received","line_id":"us","sms":{"sender":"+86138xxxxxxxx", ...}}
Pitfalls on the app side
SMS conversations open empty
Cause: URLComponents leaves a literal + in query parameters, while the server decodes + as a space under form-encoding rules. So +86138… became 86138…, with a leading space, and nothing matched.
I checked this against the live gateway: the literal form returned an empty array, the percent-encoded form returned the messages.
Fix: every phone number that goes into a query parameter is encoded in one single place, rather than separately at each call site. Conventions of the “each call site handles it itself” kind will sooner or later have someone miss one.
The second call is rejected with error code 7
Cause: error code 7 means “maximum number of call groups reached.” The CallKit provider allows only one call group, and a dial that never connected was never reported as ended, so it held that group forever.
Local state was cleared, but CallKit was never told. Clear only one side of the two and the system will go on believing that a call which doesn’t exist is still in progress.
Fix: every failure path reports the call as ended to CallKit; leftovers are cleared before starting a new call; and a dial that has neither connected nor been rejected gets a 45-second deadline.
Clearing only one side is the most common shape of bug in this kind of system integration: state lives in two places, and the code updates only its own copy.
Every call would have been silent
This bug was deduced by reading the code and walking through the timing, not hit on a real device.
Cause: CallKit hands over the audio session immediately after the dial action completes, and that happens before the audio engine is created. So the “audio session activated” callback called the start method on a nil, nothing happened, and nobody ever started it afterwards.
Fix: treat “audio session activated” and “engine created” as two events whose order isn’t fixed, and have both call the same “start if the conditions are met” function, so whichever arrives second takes effect. The engine’s own guard makes repeated calls harmless.
This kind of race deserves an extra word: an optional call on nil doesn’t crash and doesn’t report an error; it just does nothing. In Swift, the line try audio?.start(), when audio is nil, is a perfectly legal, perfectly silent no-op.
No ring while the app is in the foreground
Cause: the event stream clearly told the app “a call is ringing,” and the app did nothing, because the code that reports incoming calls lived only in the push callback.
Fix: incoming calls received in the foreground are reported to CallKit too. Both sources may fire for the same call, so one that has already been reported is skipped; otherwise two incoming-call screens appear. When the gateway says a call has ended, CallKit has to be told as well, or the incoming-call screen just hangs there with nothing ever happening next.
Crash on the very first TLS handshake
Cause: the LAN gateway uses a self-signed certificate, which has to be allowed in the URL session’s delegate method. That delegate method runs on the networking library’s own queue, and the code reached from there into main-thread-isolated data, tripping a low-level queue assertion; the process died on the first handshake.
Fix: trust the certificate only for the one configured host, not for every host; the delegate object that holds the exception keeps its own snapshot of the hostname and never touches main-thread state at all.
Two hard rules of VoIP push
Break either of these and the consequence isn’t an error; it’s punishment by the system:
- Reporting a new incoming call must be done synchronously inside the push callback. Otherwise iOS kills the process outright and throttles future push delivery.
- The audio engine must be started in CallKit’s “session activated” callback, not at dial time. Otherwise it binds to the wrong audio route and the first call has no sound.
Push on the gateway side
- Certificate-authenticated APNs over HTTP/2, with no new dependencies.
- A very quiet pitfall: in Go, as soon as you set
TLSClientConfig, automatic HTTP/2 is switched off, and APNs rejects HTTP/1.1. You have to turn onForceAttemptHTTP2explicitly. The error won’t tell you why. - Whether it’s sandbox or production is reported by the client, not guessed.
- Tokens that APNs reports as permanently invalid are deleted outright, rather than retried on every future call.
- “Ringing” in the push and in the event stream is triggered by the same state transition, which guarantees that a phone in the foreground and a phone asleep are never told different things.
- There is a status endpoint, so push failures are visible rather than silent.
Push needs your own Apple VoIP certificate; until that is configured it stays off, and the app only rings while it is in the foreground and connected to the event stream.
Testing
The unit tests decode real gateway JSON directly. If either side renames a field, it fails in the tests instead of showing up as a blank screen in the UI.
This is the cheapest kind of test in a client-plus-server project: no mocks, no running server, just real responses saved and fed to the decoder.
The bugs in this post all look alike
| Problem | Root cause |
|---|---|
| Empty conversation | + in a query parameter decoded as a space |
| Error code 7 | Only one side cleared, CallKit or local state |
| No sound | Race between audio-session activation and engine creation |
| No ring in the foreground | Only the push path reported incoming calls |
| TLS crash | Main-thread state accessed on the networking library’s queue |
| Half the events lost | Shared channel, multiple consumers |
Four of the six are the same thing: one piece of state with a copy in each of two places, and code that maintains only one copy. When you write a client that deals with system frameworks, this pattern is worth watching for at all times.
The last post: an Android tablet, with the dongle plugged into its only USB-C port, no computer and no root, and how to turn that into a phone.
The series
- What Is It, Really
- An SMS and eSIM Gateway on a Raspberry Pi
- VoWiFi from Scratch
- USB Handsets, Browser Calls and an ESP32
- On a Mac
- The iPhone Client
- An Android Tablet Drives It Directly
This series is a record of personal learning and technical research. Please comply with the laws and regulations where you are and with your carrier’s terms of service.
Comments