i am using native swift but unable to switch camer...
# ask-ai
g
i am using native swift but unable to switch camera on some devices
t
Thanks for reaching out, bisharat. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — I’m looking at your issue with camera switching on native Swift. To help diagnose and fix it quickly, could you share the following: 1. Which device models / iOS versions show the problem and which work fine? 2. The code you use to switch cameras (the
LocalVideoTrack
or
AVCapture
calls). 3. Any runtime errors, console logs, or symptom details (e.g., blank preview, freezes, camera stays on same lens). 4. Your
Info.plist
camera usage entries and whether camera permission was requested/granted at runtime. 5. Whether the devices have multiple cameras (some older devices only have one). Common checks while you gather that: • Use
LocalVideoTrack.switchCamera()
(or your capture session’s
AVCaptureDevice
swap) to switch. • Ensure camera permission is granted and both usage descriptions exist in
Info.plist
. • Verify the device actually exposes front/back cameras via
AVCaptureDevice.devices()
. Send the code and logs and I’ll suggest targeted fixes. Sources: client-sdk-swift | livekit/livekit_composite | DeepWiki | client-sdk-android | livekit/livekit_composite | DeepWiki | Camera & microphone | LiveKit docs
g
here is my function private func toggleCamera() { Task { do { guard let localParticipant = room?.localParticipant else { debugPrint("❌ Local participant not available") return } // Find the active camera track from all published tracks let cameraVideoTrack = localParticipant.trackPublications.values.compactMap { publication in // Ensure the publication source is a camera and the track is a LocalVideoTrack if publication.source == Track.Source.camera { debugPrint("📹 Found camera track: \(publication.track)") return publication.track as? LocalVideoTrack } return nil }.first guard let localVideoTrack = cameraVideoTrack else { debugPrint("❌ Camera track not found or is not a LocalVideoTrack") return } // Access the CameraCapturer associated with the track guard let cameraCapturer = localVideoTrack.capturer as? CameraCapturer else { debugPrint("❌ Camera capturer not found") return } debugPrint("🔄 Switching camera position...") // The switchCameraPosition() method automatically toggles front/back try await cameraCapturer.switchCameraPosition() // Determine the new position for logging/events (optional) let newPosition = cameraCapturer.position let positionName = (newPosition == .front) ? "front" : "back" debugPrint("✅ Camera switched to \(positionName) camera") // Assuming sendEvent is a function you have defined elsewhere // sendEvent("cameraToggled", data: ["cameraPosition": positionName]) } catch { debugPrint("❌ Failed to toggle camera: \(error.localizedDescription)") // sendEvent("cameraToggled", data: ["error": error.localizedDescription]) } } } it worked on some devices but not working some devices
t
Thanks — you’ve given a clear code sample, which helps. I’ll highlight likely causes and a few targeted checks to narrow the device-specific failure. Quick checklist to run on the devices that fail (one item per test): • Confirm the failing device exposes multiple cameras: run
Copy code
print(AVCaptureDevice.devices(for: .video))
and verify front/back devices appear. • Confirm camera permission is granted at runtime (not just Info.plist). If permission is denied the capturer may exist but switching can fail. • Add logs around
cameraCapturer.switchCameraPosition()
to capture thrown errors and stack traces. For example log
error
and
error.localizedDescription
in the catch block (you already do — confirm output). • Verify
cameraCapturer.position
before/after calling
switchCameraPosition()
to see whether position changes but UI/preview doesn’t update. • Check for concurrent access to the capture session (other camera use e.g., system camera, another app, or another AV session in your app) — that can block switching on some devices. • Confirm your LiveKit Swift SDK version is consistent across devices (older SDK/OS combos may behave differently). If those checks don’t reveal the cause, please share: 1. Device model(s) and iOS versions where it fails and one that succeeds. 2. Console logs (the debugPrint lines and the catch error text) from a failing run. 3. The value of
AVCaptureDevice.devices(for: .video)
output on a failing device. 4. Whether any other camera-using code runs concurrently. I’ll use those logs to point to a specific fix (capture session conflict, permission issue, missing camera device, or SDK/OS incompatibility). Would you like example log statements to add around the switch call?
g
these are some logs [[Back Camera][com.apple.avfoundation.avcapturedevice.built-in_video:0], [Front Camera][com.apple.avfoundation.avcapturedevice.built-in_video:1]] CameraCapturer.startCapture() starting camera capturer device: <AVCaptureFigVideoDevice: 0x12b320000 [Front Camera][com.apple.avfoundation.avcapturedevice.built-in_video:1]>, format: (format: 'vide'/'420v' 1280x 720, { 1- 30 fps}, photo dims:{1280x720,4032x2268}, fov:73.292, supports vis (max strength:Low), max zoom:128.88 (upscales @2.86), ISO:23.0-2208.0, SS:0.000021-1.000000, system exposure bias range:-2.0-2.0, supports HDR, supports high photo quality, supports Portrait Effect, supports Studio Lighting, supports Reactions, dimensions: Dimensions(1280x720)), fps: 30(0...30) LocalTrackPublication.recomputeSenderParameters() Cannot re-compute sender parameters without dimensions Failed to terminate process: Error Domain=com.apple.extensionKit.errorDomain Code=18 "(null)" UserInfo={NSUnderlyingError=0x16431cc90 {Error Domain=RBSServiceErrorDomain Code=1 "Client not entitled" UserInfo={RBSEntitlement=com.apple.runningboard.terminateprocess, NSLocalizedFailureReason=Client not entitled, RBSPermanent=true}}}
t
Thanks — helpful logs. I’m responding to the camera-switch failure on some devices and the specific log lines you shared. Likely causes and next steps to narrow the issue: 1. The device shows both front/back cameras, so hardware exists — good. 2. The line
LocalTrackPublication.recomputeSenderParameters() Cannot re-compute sender parameters without dimensions
suggests the publisher doesn’t have valid video dimensions when switching. That can prevent the track from updating properly after a camera swap. Check whether the capturer’s active format/dimensions are available immediately after switch. 3. Add logging around formats/dimensions before and after `switchCameraPosition()`: ◦ Log
cameraCapturer.position
,
cameraCapturer.activeFormat
(or active format dimensions), and the `LocalVideoTrack`’s
dimensions
(or sender params) before calling switch and inside the catch. 1. If dimensions are nil after switching, try forcing a small delay before reconfiguring sender parameters or restarting the track’s sender parameters after the switch completes: ◦ After
try await cameraCapturer.switchCameraPosition()
, read the new format/dimensions and call whatever API you use to update sender parameters so the publication has dimensions. 1. Check for concurrent capture conflicts: other AVSessions or system camera usage can cause strange behavior on some devices. Ensure no other capture is active while switching. 2. Confirm consistent LiveKit SDK + iOS versions across devices. If failing devices use older SDK or OS, behavior can differ. 3. The “Client not entitled” terminate error is unrelated to camera switching — it’s a system extension/termination permission log and can be ignored for this flow. Please send these items so I can give a targeted fix: • The LiveKit Swift SDK version and iOS version on a failing device and a working device. • Logs you get after adding format/dimensions logs (before switch, immediately after, and any catch output). • Whether you set any custom capture constraints (resolution/fps) when creating the local track. If you want, I can provide the exact log snippets to add around the switch call. Which would you prefer?
g
can you provide me how should i implement ,
t
Below is a concise Swift implementation you can use to replace your current
toggleCamera()
— it adds detailed logging, checks active format/dimensions before/after switching, waits for the new format to be available, and updates sender parameters if dimensions are missing. Paste this into your class and adjust any helper calls (like updating sender params) to match your app's APIs.
Copy code
private func toggleCamera() {
    Task {
        do {
            guard let localParticipant = room?.localParticipant else {
                debugPrint("❌ Local participant not available")
                return
            }

            // find the LocalVideoTrack whose source is camera
            let cameraVideoTrack = localParticipant.trackPublications.values.compactMap { publication -> LocalVideoTrack? in
                if publication.source == .camera {
                    return publication.track as? LocalVideoTrack
                }
                return nil
            }.first

            guard let localVideoTrack = cameraVideoTrack else {
                debugPrint("❌ Camera track not found or is not a LocalVideoTrack")
                return
            }

            guard let cameraCapturer = localVideoTrack.capturer as? CameraCapturer else {
                debugPrint("❌ Camera capturer not found")
                return
            }

            func logFormatState(prefix: String) {
                let pos = cameraCapturer.position
                debugPrint("\(prefix) position: \(pos == .front ? "front" : "back")")
                if let activeFormat = cameraCapturer.activeFormat {
                    debugPrint("\(prefix) activeFormat: \(activeFormat)")
                    // If you want to log dimensions explicitly:
                    if let dims = cameraCapturer.dimensions {
                        debugPrint("\(prefix) dimensions: \(dims.width)x\(dims.height)")
                    } else {
                        debugPrint("\(prefix) dimensions: nil")
                    }
                } else {
                    debugPrint("\(prefix) activeFormat: nil")
                }
                // If your LocalVideoTrack exposes published dimensions or sender params, log them
                debugPrint("\(prefix) localVideoTrack dimensions (if available): \(String(describing: localVideoTrack.dimensions))")
            }

            logFormatState(prefix: "BEFORE SWITCH")

            debugPrint("🔄 Attempting to switch camera position...")
            try await cameraCapturer.switchCameraPosition()
            debugPrint("🔁 switchCameraPosition() returned")

            // Wait briefly for the capturer to settle and provide a new activeFormat/dimensions.
            // Some devices may take a short time to populate dimensions after a camera swap.
            let start = Date()
            var newFormatAvailable = false
            while Date().timeIntervalSince(start) < 1.5 { // wait up to 1.5s total
                if cameraCapturer.activeFormat != nil && cameraCapturer.dimensions != nil {
                    newFormatAvailable = true
                    break
                }
                // small sleep to avoid tight loop
                try await Task.sleep(nanoseconds: 100_000_000) // 100ms
            }

            logFormatState(prefix: "AFTER SWITCH (post-wait)")

            if !newFormatAvailable {
                debugPrint("⚠️ New format/dimensions not available after switch. Attempting a short retry and reconfigure sender parameters.")
                // Optional: try a small restart or force update of sender params depending on your SDK/track API
                // Example pseudocode: updateSenderParams(from: cameraCapturer.dimensions)
                // If you have the LocalTrackPublication, update its sender params explicitly:
                if let publication = localParticipant.trackPublications.values.first(where: { $0.track === localVideoTrack }) {
                    // Log current publication sender state
                    debugPrint("Publication: \(publication.sid ?? "unknown"), current senderParameters: \(String(describing: publication.senderParameters))")
                    // If your SDK exposes a method to recompute/update sender parameters, call it here.
                    // e.g., publication.recomputeSenderParameters() or your own API call to set dimensions.
                    // If no API exists, you can optionally stop/start the capturer:
                    debugPrint("Attempting to restart capturer to force dimensions...")
                    cameraCapturer.stopCapture()
                    try await Task.sleep(nanoseconds: 150_000_000) // 150ms
                    try cameraCapturer.startCapture()
                    // wait a bit again for dimensions
                    try await Task.sleep(nanoseconds: 200_000_000)
                    logFormatState(prefix: "AFTER RESTART ATTEMPT")
                }
            }

            // final sanity log
            debugPrint("✅ Camera toggle flow complete. Current position: \(cameraCapturer.position == .front ? "front" : "back")")

        } catch {
            debugPrint("❌ Failed to toggle camera: \(error.localizedDescription)")
            // include full error for debugging
            debugPrint("Error details: \(error)")
        }
    }
}
Notes and adjustments: • The snippet uses
cameraCapturer.activeFormat
and
cameraCapturer.dimensions
. If your LiveKit version uses different property names, replace accordingly. • If your SDK exposes an API to explicitly recompute or set sender parameters on the publication (e.g.,
recomputeSenderParameters()
or
publication.setSenderParameters(...)
), call that after the switch and after dimensions are available. • The restart path (stop/start capture) is a defensive measure for devices that don't populate dimensions immediately; use it only if safe in your app flow. • If you still see "Cannot re-compute sender parameters without dimensions", capture and share the BEFORE/AFTER logs produced by these additions and the SDK + iOS versions. I can then suggest a precise call to update sender parameters. Would you like a version of this that directly updates publication sender parameters (if you can share the exact LiveKit API on your SDK version)?
g
facing some errors on provided code Value of optional type 'AVCaptureDevice?' must be unwrapped to refer to member 'activeFormat' of wrapped base type 'AVCaptureDevice' /Users/bisharatjunejo/code/app/ios/Runner/LiveKitNativeManagee
t
Thanks — the compile error means
cameraCapturer.activeFormat
(an
AVCaptureDevice?
or similar) must be safely unwrapped before accessing its properties. Below is a corrected, concise
toggleCamera()
that unwraps optionals, logs formats/dimensions safely, waits for the new format, and retries by restarting capture if needed. Replace any property names if your LiveKit version differs.
Copy code
private func toggleCamera() {
    Task {
        do {
            guard let localParticipant = room?.localParticipant else {
                debugPrint("❌ Local participant not available")
                return
            }

            let cameraVideoTrack = localParticipant.trackPublications.values.compactMap { publication -> LocalVideoTrack? in
                if publication.source == .camera {
                    return publication.track as? LocalVideoTrack
                }
                return nil
            }.first

            guard let localVideoTrack = cameraVideoTrack else {
                debugPrint("❌ Camera track not found or is not a LocalVideoTrack")
                return
            }

            guard let cameraCapturer = localVideoTrack.capturer as? CameraCapturer else {
                debugPrint("❌ Camera capturer not found")
                return
            }

            func logFormatState(prefix: String) {
                let pos = cameraCapturer.position
                debugPrint("\(prefix) position: \(pos == .front ? "front" : "back")")
                if let activeFormat = cameraCapturer.activeFormat {
                    debugPrint("\(prefix) activeFormat: \(activeFormat)")
                    if let dims = cameraCapturer.dimensions {
                        debugPrint("\(prefix) dimensions: \(dims.width)x\(dims.height)")
                    } else {
                        debugPrint("\(prefix) dimensions: nil")
                    }
                } else {
                    debugPrint("\(prefix) activeFormat: nil")
                }
                debugPrint("\(prefix) localVideoTrack dimensions: \(String(describing: localVideoTrack.dimensions))")
            }

            logFormatState(prefix: "BEFORE SWITCH")

            debugPrint("🔄 Attempting to switch camera position...")
            try await cameraCapturer.switchCameraPosition()
            debugPrint("🔁 switchCameraPosition() returned")

            // Wait up to 1.5s for new format/dimensions to become available
            let start = Date()
            var newFormatAvailable = false
            while Date().timeIntervalSince(start) < 1.5 {
                if cameraCapturer.activeFormat != nil && cameraCapturer.dimensions != nil {
                    newFormatAvailable = true
                    break
                }
                try await Task.sleep(nanoseconds: 100_000_000) // 100ms
            }

            logFormatState(prefix: "AFTER SWITCH (post-wait)")

            if !newFormatAvailable {
                debugPrint("⚠️ New format/dimensions not available after switch. Attempting restart...")
                // Defensive restart: stop/start capture to force format/dimensions update
                cameraCapturer.stopCapture()
                try await Task.sleep(nanoseconds: 150_000_000) // 150ms
                try cameraCapturer.startCapture()
                try await Task.sleep(nanoseconds: 200_000_000)
                logFormatState(prefix: "AFTER RESTART ATTEMPT")
            }

            debugPrint("✅ Camera toggle flow complete. Current position: \(cameraCapturer.position == .front ? "front" : "back")")

        } catch {
            debugPrint("❌ Failed to toggle camera: \(error.localizedDescription)")
            debugPrint("Error details: \(error)")
        }
    }
}
If you still see the optional error, confirm the types of
cameraCapturer.activeFormat
and
cameraCapturer.dimensions
in your LiveKit SDK — adjust the
if let
checks to match (for example,
if let activeFormat = cameraCapturer.activeFormat as? AVCaptureDevice.Format
). Send the exact line/compile message if it persists and I’ll update the snippet.