-
Notifications
You must be signed in to change notification settings - Fork 163
Description
iOS WebSocket Connection Fails Immediately After Token Validation
Environment
- LiveKit Swift SDK Version: 2.10.1
- iOS Version: 18.6.2 or last version
- Device: iPad and iphone
- Server: LiveKit Cloud (wss://drive-hos-nd2zuy8a.livekit.cloud)
- Network: Uzbekistan → Stockholm region
- Integration: CallKit-based VoIP application
Description
iOS client consistently fails to establish WebSocket connection with LiveKit server despite successful token validation. The connection terminates immediately with NSURLError -1005 ("Connection not set before response is received"). Android clients connecting to the same server with identical tokens work perfectly.
Expected Behavior
After token validation succeeds, the WebSocket connection should establish and the client should join the room successfully.
Actual Behavior
- Token validation returns "success"
- WebSocket connection attempt begins
- Connection hangs for ~1 second
- Connection terminates with error -1005
- Room state transitions:
disconnected→connecting→disconnected
Steps to Reproduce
- Setup CallKit Integration
let provider = CXProvider(configuration: CXProviderConfiguration())
provider.setDelegate(self, queue: nil)- Configure Audio Session in CallKit Delegate
func provider(_ provider: CXProvider, didActivate audioSession: AVAudioSession) {
try audioSession.setCategory(.playAndRecord, mode: .voiceChat)
try audioSession.setActive(true)
}- Initialize LiveKit Room
let roomOptions = RoomOptions()
let room = Room(delegate: self, roomOptions: roomOptions)- Attempt Connection
try await room.connect(
url: "wss://drive-hos-nd2zuy8a.livekit.cloud",
token: validToken
)Logs
Console Output:
Room.connect(url:token:connectOptions:roomOptions:) Connecting to room...
Connection not set before response is received, failing task
Task <48478415-9E0C-4CDC-A801-E86B60D8EFBC>.<1> finished with error [-1005]
Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."
WebSocket.urlSession(_:task:didCompleteWithError:) didCompleteWithError
RoomDelegate callback:
room(_:didUpdateConnectionState:from:)
- From: .connecting
- To: .disconnected
Error: Network error(Validation response: "success")
Domain: io.livekit.swift-sdk
Code: 202
Token Validation Timeline:
12:30:51 - Connection state: .connecting
12:30:51 - Token validation: "success" ✅
12:30:52 - NSURLError -1005 ❌
12:30:52 - Connection state: .disconnected
App State During Connection:
App State: active (0) - Verified throughout entire process
CallKit Audio Session: active ✅
Background Task: running ✅
Code Sample
Minimal Reproducible Example
```swift import LiveKit import CallKit import AVFoundation@mainactor
class LiveKitService: ObservableObject {
private var room: Room?
func connect(url: String, token: String) async throws {
let roomOptions = RoomOptions()
let newRoom = Room(delegate: self, roomOptions: roomOptions)
self.room = newRoom
// Fails here with -1005
try await newRoom.connect(url: url, token: token)
try await newRoom.localParticipant.setMicrophone(enabled: true)
}
}
extension LiveKitService: RoomDelegate {
nonisolated func room(_ room: Room, didUpdateConnectionState connectionState: ConnectionState, from oldConnectionState: ConnectionState) {
print("State: (oldConnectionState) → (connectionState)")
}
nonisolated func room(_ room: Room, didFailToConnectWithError error: LiveKitError?) {
print("Failed: \(error?.localizedDescription ?? "unknown")")
}
}
</details>
### Additional Context
**Working Scenario:**
- ✅ Android client (Kotlin): Connects successfully
- ✅ Web client (JavaScript): Connects successfully
- ✅ Same backend-generated tokens work on Android/Web
- ✅ Same LiveKit Cloud project
**Failing Scenario:**
- ❌ iOS client (Swift 2.9.0): Fails with -1005
- ❌ Both real device and simulator
- ❌ Consistent 100% failure rate
- ❌ Tested with both backend tokens and dashboard-generated tokens
**Network Tests:**
```bash
# Server reachable
$ curl -I https://drive-hos-nd2zuy8a.livekit.cloud
HTTP/2 200
# DNS resolves correctly
$ nslookup drive-hos-nd2zuy8a.livekit.cloud
Address: 13.48.23.95
# WebSocket endpoint accessible (returns 401 as expected without token)
$ websocat wss://drive-hos-nd2zuy8a.livekit.cloud/rtc
401 Unauthorized
Token Example (decoded JWT):
{
"exp": 1765132240,
"identity": "0b91c4e4-279c-4015-9a13-5d997b14fa17",
"iss": "APIRprzHcrJ2nSd",
"nbf": 1765110640,
"video": {
"canPublish": true,
"canSubscribe": true,
"room": "daa64ab1add158c7598b8af412265a65",
"roomJoin": true
}
}LiveKit Dashboard Activity:
- Sessions show iOS connections briefly appearing (5-20 seconds)
- Then immediately closing
- No error messages in dashboard
- Android sessions remain stable
Attempted Solutions
- ✅ Tested without CallKit - Same error
- ✅ Tried different ConnectOptions - No change
iceTransportPolicy: .relay(force TURN)iceTransportPolicy: .all(default)
- ✅ Delayed connection (3+ seconds) - No change
- ✅ Verified audio session active - Confirmed working
- ✅ Ensured app state is active - Verified
- ✅ Upgraded to SDK 2.10.x - (if applicable after testing)
Questions
- Is there a known iOS-specific issue with version 2.9.0?
- Could this be related to URLSession configuration in the SDK?
- Are there server-side restrictions or timeouts specific to iOS clients?
- Should we be using custom URLSessionConfiguration?
- Is CallKit integration known to cause this issue?
Request
Could you please investigate why token validation succeeds but WebSocket connection immediately fails on iOS? The error message "Connection not set before response is received" suggests the connection is being terminated by iOS before the response arrives, but we've verified the app remains active and all permissions are granted.
Device Specifications
- Model: iPad (iPad14,3)
- OS: iOS 18.6.2
- Architecture: arm64
- Network: WiFi/Cellular (tested both)
Project Information
- LiveKit Cloud Project: Drive HoS
- Region: Stockholm (nd2zuy8a)
- API Key: APIRprzHcrJ2nSd (masked)
Would greatly appreciate any insights or guidance! 🙏
Android works perfectly with identical setup, so this appears to be iOS SDK specific.
---
# 📋 Issue yuborishdan oldin:
## 1️⃣ Title tanlang:
iOS: WebSocket Connection Fails with -1005 After Successful Token Validation
yoki
iOS: "Connection not set before response is received" Error on Room.connect()
## 2️⃣ Labels qo'shing (agar mavjud bo'lsa):
- `bug`
- `ios`
- `help wanted`
- `connection`
## 3️⃣ Link:
https://github.com/livekit/client-sdk-swift/issues
---
# 💡 Qo'shimcha Tips:
1. **Attach screenshot** - Dashboard Sessions page
2. **Mention urgency** - Agar production'da bo'lsa
3. **Offer to test** - "Happy to test any fixes or provide more logs"
4. **Tag maintainers** - Agar bilsangiz: `@username`
---
# 📎 Reproducible Example Repository (Optional):
Agar mumkin bo'lsa, minimal test project GitHub'ga upload qiling:
MyLiveKitTest/
├── ContentView.swift
├── LiveKitService.swift
├── Info.plist (VoIP configuration)
└── README.md (steps to reproduce)