# Camera scanning with SocketCam

Implement camera-based barcode scanning with SocketCam in CaptureSDK. Covers enabling SocketCam, handling SocketCam device presence events, and three camera presentation modes: fullscreen overlay, embedded subview within your UI, and popover. Also covers configuring continuous scanning mode, customizing the close button appearance, and triggering scans programmatically. SocketCam uses the same Capture Helper delegate events as physical scanners. Includes code samples for each mode.

## Device presence

On some platforms, SocketCam is enabled by default so the **Capture Helper device arrival event** is triggered automatically. If it's not, refer to the section [Enabling SocketCam](#enabling-socketcam)

## Java

```java
private DeviceClient mSocketCamDevice;

@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void onCaptureDeviceStateChange(DeviceStateEvent event) {
    DeviceClient device = event.getDevice();
    DeviceState state = event.getState();
    int deviceType = device.getDeviceType();
    Log.d(TAG, "onCaptureDeviceStateChange: " + device.getDeviceName() + " - State: " + state);

    if (DeviceType.isCameraScanner(deviceType)) {
        switch (state.intValue()) {
            case DeviceState.READY:
                // handle SocketCam device arrival - Retains it to later trigger the camera scanning
                mSocketCamDevice = device;
                break;
            case DeviceState.GONE:
                // handle SocketCam device removal - Releases the reference
                mSocketCamDevice = null;
                break;
        }
    }
}
```

## Kotlin

```kotlin
private var socketCamDevice: DeviceClient? = null

@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
fun onCaptureDeviceStateChange(event: DeviceStateEvent) {
    val device: DeviceClient = event.device
    val state: DeviceState = event.state
    val deviceType = device.deviceType
    Log.d(TAG, "onCaptureDeviceStateChange: ${device.deviceName} - State: $state")

    if (DeviceType.isCameraScanner(deviceType)) {
        when (state.intValue()) {
            // handle SocketCam device arrival - Retains it to later trigger the camera scanning
            DeviceState.READY -> socketCamDevice = device
            // handle SocketCam device removal - Releases the reference
            DeviceState.GONE -> socketCamDevice = null
        }
    }
}
```

## Swift

```swift
var socketCamDevice: CaptureHelperDevice?

extension MyViewController: CaptureHelperDevicePresenceDelegate {

  func didNotifyArrivalForDevice(_ device: CaptureHelperDevice, withResult result: SKTResult) {
      print("didNotifyArrivalForDevice: \(device.deviceInfo.name ?? "") - Result: \(result.rawValue)")
      if device.deviceInfo.deviceType = .socketCamC820 || device.deviceInfo.deviceType = .socketCamC860 {
          // handle SocketCam device arrival - Retains it to later trigger the camera scanning
          socketCamDevice = device
      }
  }

  func didNotifyRemovalForDevice(_ device: CaptureHelperDevice, withResult result: SKTResult) {
      print("didNotifyRemovalForDevice: \(device.deviceInfo.name ?? "") - Result: \(result.rawValue)")
      if device.deviceInfo.deviceType = .socketCamC820 || device.deviceInfo.deviceType = .socketCamC860 {
          // handle SocketCam device removal - Destroying the object
          socketCamDevice = nil
      }
  }

}
```

## C#

```csharp
private CaptureHelperDevice _socketCamDevice;

private static bool IsSocketCam(CaptureHelperDevice device)
{
    int type = device.GetDeviceInfo().Type;
    return type == DeviceTypes.kSocketCamC820 || type == DeviceTypes.kSocketCamC860;
}

void CaptureDeviceArrival(object sender, CaptureHelper.DeviceArgs e)
{
    Console.WriteLine($"Device arrival: {e.CaptureDevice.GetDeviceInfo().Name} - Result: {e.Result}");
    if (IsSocketCam(e.CaptureDevice))
    {
        // handle SocketCam device arrival - Retains it to later trigger the camera scanning
        _socketCamDevice = e.CaptureDevice;
    }
}

void CaptureDeviceRemoval(object sender, CaptureHelper.DeviceArgs e)
{
    Console.WriteLine($"Device removal: {e.CaptureDevice.GetDeviceInfo().Name} - Result: {e.Result}");
    if (IsSocketCam(e.CaptureDevice))
    {
        // handle SocketCam device removal - Releasing the object
        _socketCamDevice = null;
    }
}
```

## Dart

```dart
CaptureHelperDevice? socketCamDevice;

await helper.open(
  appInfo,
  onDeviceArrival: (CaptureHelperDevice device) {
    debugPrint('Device arrival: ${device.name}');
    // SocketCamTypes contains CaptureDeviceType.socketCamC820 and CaptureDeviceType.socketCamC860
    if (SocketCamTypes.contains(device.type)) {
      // handle SocketCam device arrival - Retains it to later trigger the camera scanning
      socketCamDevice = device;
    }
  },
  onDeviceRemoval: (CaptureHelperDevice device) {
    debugPrint('Device removal: ${device.name}');
    if (SocketCamTypes.contains(device.type)) {
      // handle SocketCam device removal - Destroying the object
      socketCamDevice = null;
    }
  },
);

// The SocketCam device can also be retrieved at any time from CaptureHelper
socketCamDevice = helper.getSocketCamDevice();
```

## JavaScript

```javascript
import { useState } from 'react';
import { CaptureHelper, SocketCamTypes } from 'react-native-capture';

const [socketCamDevice, setSocketCamDevice] = useState(null);

const helper = new CaptureHelper({
  appInfo,

  onDeviceArrival: (device) => {
    console.log(`Device arrival: ${device.name}`);
    if (SocketCamTypes.indexOf(device.type) > -1) {
      // handle SocketCam (C820 or C860) device arrival - Retains it to later trigger the camera scanning
      setSocketCamDevice(device);
    }
  },

  onDeviceRemoval: (device) => {
    console.log(`Device removal: ${device.name}`);
    if (SocketCamTypes.indexOf(device.type) > -1) {
      // handle SocketCam device removal
      setSocketCamDevice(null);
    }
  },
});
```

## Using SocketCam

Now the application is ready to use the camera as a barcode scanner. Usually an application shows a "Scan trigger" button somewhere in the UI to start scanning for a barcode.

> **Note**
>
> Applications can use physical buttons such as the volume up or down button to act as a trigger button.

The way to start the scanning operation is by sending the **setTrigger property**. On Android, use the `trigger()` and `triggerContinuous()` methods of the device. With React Native, the **SocketCamViewContainer** component sends the trigger when its `openSocketCamView` prop becomes `true`.

- The view closes once a barcode is scanned.
- The decoded data are sent in a **decoded data event** as it does for any other physical scanner.
- [Trigger continuous](#triggering-socketcam-in-continuous-mode) mode will launch the SocketCam view and continue to scan barcodes until the view is dismissed by the user. You can store the scanned barcodes into an array for instance.

## Triggering SocketCam

With CaptureSDK, you will be able to present SocketCam as you wish in a custom view, a popover and still in full screen. Now you decide where and when triggering and removing SocketCam view in your application's flow. 

> **Warning**
>
> This is your responsibility to handle the presentation and the dismissal of the view.
>
> Also, there's a minimal size of 250px x 250px to observe in order to display all SocketCam's UI elements as a subview or a popover.

> **Note**
>
> On Android, and on Windows with MAUI, the full screen SocketCam view is presented and dismissed by CaptureSDK itself. Only a custom view requires your application to handle it.

## Sample code for SocketCam presented in Full screen

## Java

```java
private DeviceClient mSocketCamDevice;

// No CustomViewListener is set on the CaptureExtension: triggering SocketCam
// launches the default SocketCam viewfinder Activity in full screen.
public void onScanButtonClicked(View view) {
    if (mSocketCamDevice == null) {
        return;
    }
    mSocketCamDevice.trigger(new PropertyCallback() {
        @Override
        public void onComplete(CaptureError error, Property property) {
            if (error != null) {
                Log.e(TAG, "SocketCam trigger failed: " + error.getMessage());
            }
        }
    });
}

// This handler is called each time a decoded data is read from a scanner or SocketCam
@Subscribe(threadMode = ThreadMode.MAIN)
public void onScan(DataEvent event) {
    DecodedData data = event.getData();
    Log.d(TAG, "onScan for device: " + event.getDevice().getDeviceType());
    if (data.result == DecodedData.RESULT_SUCCESS) {
        Log.d(TAG, "Decoded Data " + data.getString());
    } else {
        // the user closed the SocketCam viewfinder without scanning a barcode
        Log.d(TAG, "SocketCam scan cancelled");
    }
    // The SocketCam viewfinder closes by itself once a barcode is scanned
}
```

## Kotlin

```kotlin
private var socketCamDevice: DeviceClient? = null

// No CustomViewListener is set on the CaptureExtension: triggering SocketCam
// launches the default SocketCam viewfinder Activity in full screen.
fun onScanButtonClicked(view: View) {
    socketCamDevice?.trigger { error, _ ->
        if (error != null) {
            Log.e(TAG, "SocketCam trigger failed: ${error.message}")
        }
    }
}

// This handler is called each time a decoded data is read from a scanner or SocketCam
@Subscribe(threadMode = ThreadMode.MAIN)
fun onScan(event: DataEvent) {
    val data: DecodedData = event.data
    Log.d(TAG, "onScan for device: ${event.device.deviceType}")
    if (data.result == DecodedData.RESULT_SUCCESS) {
        Log.d(TAG, "Decoded Data ${data.string}")
    } else {
        // the user closed the SocketCam viewfinder without scanning a barcode
        Log.d(TAG, "SocketCam scan cancelled")
    }
    // The SocketCam viewfinder closes by itself once a barcode is scanned
}
```

## Swift

```swift
var socketCamDevice: CaptureHelperDevice?
var mySocketCamViewController: UIViewController?

// The signature of the method to trigger SocketCam has now an extra return parameter: propertyObject. 
// It contains a dictionary that contains the SocketCam view controller that you can use as you wish in full screen, as a subview or a popover.

socketCamDevice.setTrigger(.start, withCompletionHandler: { result, propertyObject in
    DispatchQueue.main.async {
        if let anObject = propertyObject?.object,
           let dic = anObject as? [String: Any],
           let objectType = dic["SKTObjectType"] as? String, objectType == "SKTSocketCamViewControllerType",
           let socketCamViewController = dic["SKTSocketCamViewController"] as? UIViewController {
                socketCamViewController.modalPresentationStyle = .fullScreen
                self.present(socketCamViewController, animated: true)
                // retain the socketcam view controller for the dismissal later
                self.mySocketCamViewController = socketCamViewController
        }
    }
})

extension MyViewController: CaptureHelperDeviceDecodedDataDelegate {
    // This delegate is called each time a decoded data is read from a scanner or SocketCam
    func didReceiveDecodedData(_ decodedData: SKTCaptureDecodedData?, fromDevice device: CaptureHelperDevice, withResult result:SKTResult) {
        print("--->>> didReceiveDecodedData for device: \(device.deviceInfo.deviceType)")
        if result == .E_NOERROR {
            let str = decodedData!.stringFromDecodedData()
            print("Decoded Data \(String(describing: str))")
        }
        DispatchQueue.main.async {
            // Dismiss and reset your socketCamViewController
            self.mySocketCamViewController?.dismiss(animated: true, completion: {
                self.mySocketCamViewController = nil
            })
        }
    }
}
```

## C#

```csharp
private CaptureHelperDevice _socketCamDevice;
#if __IOS__
private UIViewController _socketCamViewController;
#endif

private async void ButtonTrigger_Clicked(object sender, EventArgs e)
{
    var triggerResult = await _socketCamDevice.SetTriggerAsync(ICaptureProperty.Values.Trigger.kStart);

#if __IOS__
    // iOS: ResultObject contains a dictionary with the SocketCam view controller to present
    if (triggerResult.ResultObject is NSDictionary dictionary &&
        dictionary[NSObject.FromObject("SKTObjectType")] is NSString objectType &&
        objectType == "SKTSocketCamViewControllerType" &&
        dictionary[NSObject.FromObject("SKTSocketCamViewController")] is UIViewController socketCamViewController)
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            socketCamViewController.ModalPresentationStyle = UIModalPresentationStyle.FullScreen;
            Platform.GetCurrentUIViewController()?.PresentViewController(socketCamViewController, true, null);
            // retain the SocketCam view controller for the dismissal later
            _socketCamViewController = socketCamViewController;
        });
    }
#endif
    // Android and Windows: SocketCam is displayed in full screen by CaptureSDK and closes after a scan
}

// This event is fired each time a decoded data is read from a scanner or SocketCam
void CaptureDecodedData(object sender, CaptureHelper.DecodedDataArgs e)
{
    if (SktErrors.SKTSUCCESS(e.Result))
    {
        Console.WriteLine($"Decoded Data: {e.DecodedData.DataToUTF8String}");
    }

#if __IOS__
    MainThread.BeginInvokeOnMainThread(() =>
    {
        // Dismiss and reset your SocketCam view controller
        _socketCamViewController?.DismissViewController(true, null);
        _socketCamViewController = null;
    });
#endif
}
```

## Dart

```dart
CaptureHelperDevice? socketCamDevice;

Future<void> triggerSocketCam() async {
  final CaptureHelperDevice? device = socketCamDevice;
  if (device == null) {
    return;
  }
  try {
    // Android: the SDK opens its own full-screen camera Activity
    await device.setTrigger(Trigger.start);
    // iOS: presents the SocketCam view controller in full screen (does nothing on Android)
    await SocketCamView.presentFullScreen();
  } on CaptureException catch (e) {
    debugPrint('SetTrigger error: ${e.code} ${e.message}');
  }
}

await helper.open(
  appInfo,
  // Called each time a decoded data is read from a scanner or SocketCam.
  // The SocketCam full-screen view closes automatically once a barcode is scanned.
  onDecodedData: (DecodedData data, CaptureHelperDevice device) {
    debugPrint('Decoded Data from ${device.name}: ${data.dataAsString()}');
  },
  // Called when the user closes SocketCam without scanning a barcode
  onSocketCamCanceled: (CaptureHelperDevice device) {
    debugPrint('SocketCam canceled');
  },
);
```

## JavaScript

```javascript
import { useEffect, useState } from 'react';
import { Button, View } from 'react-native';
import {
  CaptureHelper,
  SocketCamTypes,
  SocketCamViewContainer,
  Trigger,
} from 'react-native-capture';

const ScanScreen = () => {
  const [rootCapture, setRootCapture] = useState(null);
  const [socketCamDevice, setSocketCamDevice] = useState(null);
  const [openSocketCamView, setOpenSocketCamView] = useState(false);

  useEffect(() => {
    const helper = new CaptureHelper({
      appInfo,

      onDeviceArrival: (device) => {
        if (SocketCamTypes.indexOf(device.type) > -1) {
          setSocketCamDevice(device);
        }
      },

      // Called each time a decoded data is read from a scanner or SocketCam
      onDecodedData: (data, device) => {
        console.log(`Decoded Data: ${String.fromCharCode(...data.data)}`);
        if (SocketCamTypes.indexOf(device.type) > -1) {
          // Close the SocketCam view after a single scan
          setOpenSocketCamView(false);
        }
      },

      // Called when the user closes the SocketCam view with its close button
      onSocketCamCanceled: () => {
        setOpenSocketCamView(false);
      },
    });

    helper
      .open()
      .then(() => setRootCapture(helper.rootCapture))
      .catch(() => {});

    return () => {
      helper.close().catch(() => {});
    };
  }, []);

  return (
    <View style={{ flex: 1 }}>
      {/* SocketCamViewContainer sends the trigger when openSocketCamView becomes true */}
      <Button
        title="Scan"
        disabled={!socketCamDevice}
        onPress={() => setOpenSocketCamView(true)}
      />
      {rootCapture && (
        <SocketCamViewContainer
          openSocketCamView={openSocketCamView}
          triggerType={Trigger.Start}
          clientOrDeviceHandle={rootCapture.clientOrDeviceHandle}
          socketCamCapture={rootCapture}
          socketCamDevice={socketCamDevice}
          handleSetSocketCamEnabled={() => {}}
        />
      )}
    </View>
  );
};
```

## Sample code for SocketCam presented as a subview

On Android, SocketCam is displayed in your own Activity with **SocketCamFragment** once the **CustomViewListener** of the CaptureExtension is called. The embedded view is not available on Android with Flutter and MAUI.

## Java

```java
private static final int PERMISSION_REQUEST_CAMERA = 0x10;

private DeviceClient mSocketCamDevice;
private SocketCamFragment mSocketCamFragment;

// Setting a CustomViewListener when building the CaptureExtension tells CaptureSDK
// not to launch the default viewfinder: onViewReady() is called instead when SocketCam is triggered.
// Build it in onCaptureServiceConnectionStateChange() once the Capture client is READY (see Enabling SocketCam).
mCaptureExtension = new CaptureExtension.Builder()
        .setContext(getApplicationContext())
        .setClientHandle(mCaptureClient.getHandle())
        .setExtensionScope(ExtensionScope.LOCAL)
        .setListener(mExtensionListener)
        .setCustomViewListener(new CaptureExtension.CustomViewListener() {
            @Override
            public void onViewReady(int deviceHandle) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // false: single scan mode - true: continuous scan mode
                        mSocketCamFragment = SocketCamFragment.newInstance(deviceHandle, false);
                        // R.id.socketcam_container is a view of your choosing in your Activity layout
                        getSupportFragmentManager().beginTransaction()
                                .add(R.id.socketcam_container, mSocketCamFragment)
                                .commit();
                    }
                });
            }
        })
        .build();
mCaptureExtension.start();

// With a custom viewfinder, the application is responsible for the camera permission
public void onScanButtonClicked(View view) {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CAMERA);
    } else {
        triggerSocketCam();
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == PERMISSION_REQUEST_CAMERA && grantResults.length > 0
            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        triggerSocketCam();
    }
}

private void triggerSocketCam() {
    if (mSocketCamDevice == null) {
        return;
    }
    mSocketCamDevice.trigger(new PropertyCallback() {
        @Override
        public void onComplete(CaptureError error, Property property) {
            if (error != null) {
                Log.e(TAG, "SocketCam trigger failed: " + error.getMessage());
            }
        }
    });
}

// This handler is called each time a decoded data is read from a scanner or SocketCam
@Subscribe(threadMode = ThreadMode.MAIN)
public void onScan(DataEvent event) {
    DecodedData data = event.getData();
    if (data.result == DecodedData.RESULT_SUCCESS) {
        Log.d(TAG, "Decoded Data " + data.getString());
    }
    // Remove the SocketCam fragment from your Activity and reset it
    if (mSocketCamFragment != null) {
        getSupportFragmentManager().beginTransaction()
                .remove(mSocketCamFragment)
                .commit();
        mSocketCamFragment = null;
    }
}
```

## Kotlin

```kotlin
companion object {
    private const val PERMISSION_REQUEST_CAMERA = 0x10
}

private var socketCamDevice: DeviceClient? = null
private var socketCamFragment: SocketCamFragment? = null

// Setting a CustomViewListener when building the CaptureExtension tells CaptureSDK
// not to launch the default viewfinder: onViewReady() is called instead when SocketCam is triggered.
// Build it in onCaptureServiceConnectionStateChange() once the Capture client is READY (see Enabling SocketCam).
captureExtension = CaptureExtension.Builder()
    .setContext(applicationContext)
    .setClientHandle(client.handle)
    .setExtensionScope(ExtensionScope.LOCAL)
    .setListener(extensionListener)
    .setCustomViewListener { deviceHandle ->
        runOnUiThread {
            // false: single scan mode - true: continuous scan mode
            val fragment = SocketCamFragment.newInstance(deviceHandle, false)
            socketCamFragment = fragment
            // R.id.socketcam_container is a view of your choosing in your Activity layout
            supportFragmentManager.beginTransaction()
                .add(R.id.socketcam_container, fragment)
                .commit()
        }
    }
    .build()
captureExtension?.start()

// With a custom viewfinder, the application is responsible for the camera permission
fun onScanButtonClicked(view: View) {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), PERMISSION_REQUEST_CAMERA)
    } else {
        triggerSocketCam()
    }
}

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    if (requestCode == PERMISSION_REQUEST_CAMERA && grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) {
        triggerSocketCam()
    }
}

private fun triggerSocketCam() {
    socketCamDevice?.trigger { error, _ ->
        if (error != null) {
            Log.e(TAG, "SocketCam trigger failed: ${error.message}")
        }
    }
}

// This handler is called each time a decoded data is read from a scanner or SocketCam
@Subscribe(threadMode = ThreadMode.MAIN)
fun onScan(event: DataEvent) {
    val data: DecodedData = event.data
    if (data.result == DecodedData.RESULT_SUCCESS) {
        Log.d(TAG, "Decoded Data ${data.string}")
    }
    // Remove the SocketCam fragment from your Activity and reset it
    socketCamFragment?.let {
        supportFragmentManager.beginTransaction()
            .remove(it)
            .commit()
    }
    socketCamFragment = null
}
```

## Swift

```swift
var socketCamDevice: CaptureHelperDevice?
var mySocketCamViewController: UIViewController?
var mySocketCamView: UIView? // can be also an @IBOutlet

// The signature of the method to trigger SocketCam has now an extra return parameter: propertyObject. 
// It contains a dictionary that contains the SocketCam view controller that you can use as you wish in full screen, as a subview or a popover.

socketCamDevice.setTrigger(.start, withCompletionHandler: { result, propertyObject in
    DispatchQueue.main.async {
        if let anObject = propertyObject?.object,
           let dic = anObject as? [String: Any],
           let objectType = dic["SKTObjectType"] as? String, objectType == "SKTSocketCamViewControllerType",
           let socketCamViewController = dic["SKTSocketCamViewController"] as? UIViewController {
                self.mySocketCamViewController.view.frame = self.mySocketCamView.bounds
                self.mySocketCamView?.addSubview(socketCamViewController.view)
                // retain the socketcam view controller for the dismiss later
                self.mySocketCamViewController = socketCamViewController
        }
    }
})

extension MyViewController: CaptureHelperDeviceDecodedDataDelegate {
    // This delegate is called each time a decoded data is read from a scanner or SocketCam
    func didReceiveDecodedData(_ decodedData: SKTCaptureDecodedData?, fromDevice device: CaptureHelperDevice, withResult result:SKTResult) {
        print("--->>> didReceiveDecodedData for device: \(device.deviceInfo.deviceType)")
        if result == .E_NOERROR {
            let str = decodedData!.stringFromDecodedData()
            print("Decoded Data \(String(describing: str))")
        }
        DispatchQueue.main.async {
            // Remove your socketCamViewController view from the parent and reset it
            self.mySocketCamViewController?.view.removeFromSuperview()
            self.mySocketCamViewController = nil
        }
    }
}
```

## C#

```csharp
// Not available on Android: SocketCam is always displayed in full screen
private CaptureHelperDevice _socketCamDevice;
#if __IOS__
private UIViewController _socketCamViewController;
#elif WINDOWS
private CaptureExtension _captureExtension;
// SocketCamContainer is a ContentView of your page (minimum size: 250 x 250)
#endif

#if WINDOWS
private async Task StartCaptureExtensionAsync(string appId, string developerId, string appKey)
{
    _captureExtension = new CaptureExtension(Window, _capture.GetHandle(), appId, developerId, appKey);
    // Subscribing to this event replaces the default full screen view by a view you display yourself
    _captureExtension.SocketCamView += CaptureExtension_SocketCamView;
    await _captureExtension.Start();
}

// Fired each time SocketCam is triggered, with the SocketCam view to display
private void CaptureExtension_SocketCamView(object sender, SocketCamViewEventArgs e)
{
    MainThread.BeginInvokeOnMainThread(() =>
    {
        SocketCamContainer.Content = (View)e.SocketCamView;
    });
}
#endif

private async void ButtonTrigger_Clicked(object sender, EventArgs e)
{
    var triggerResult = await _socketCamDevice.SetTriggerStartAsync();

#if __IOS__
    if (triggerResult.ResultObject is NSDictionary dictionary &&
        dictionary[NSObject.FromObject("SKTObjectType")] is NSString objectType &&
        objectType == "SKTSocketCamViewControllerType" &&
        dictionary[NSObject.FromObject("SKTSocketCamViewController")] is UIViewController socketCamViewController)
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            var currentViewController = Platform.GetCurrentUIViewController();
            // position and dimensions of the SocketCam view (minimum size: 250 x 250)
            socketCamViewController.View.Frame = new CoreGraphics.CGRect(0, 0, 250, 250);
            currentViewController?.View?.AddSubview(socketCamViewController.View);
            // retain the SocketCam view controller for the removal later
            _socketCamViewController = socketCamViewController;
        });
    }
#endif
}

// This event is fired each time a decoded data is read from a scanner or SocketCam
void CaptureDecodedData(object sender, CaptureHelper.DecodedDataArgs e)
{
    if (SktErrors.SKTSUCCESS(e.Result))
    {
        Console.WriteLine($"Decoded Data: {e.DecodedData.DataToUTF8String}");
    }

    MainThread.BeginInvokeOnMainThread(() =>
    {
#if __IOS__
        // Remove the SocketCam view from its parent and reset it
        _socketCamViewController?.View?.RemoveFromSuperview();
        _socketCamViewController = null;
#elif WINDOWS
        // Remove the SocketCam view from your page
        SocketCamContainer.Content = null;
#endif
    });
}
```

## Dart

```dart
// iOS only: on Android, SocketCam is always displayed in full screen
class ScanPage extends StatefulWidget {
  const ScanPage({super.key, required this.socketCamDevice});

  final CaptureHelperDevice socketCamDevice;

  @override
  State<ScanPage> createState() => _ScanPageState();
}

class _ScanPageState extends State<ScanPage> {
  bool _showSocketCam = false;

  Future<void> _triggerSocketCam() async {
    try {
      // setTrigger must complete before mounting SocketCamView
      await widget.socketCamDevice.setTrigger(Trigger.start);
      setState(() => _showSocketCam = true);
    } on CaptureException catch (e) {
      debugPrint('SetTrigger error: ${e.code} ${e.message}');
    }
  }

  // Call it from the onDecodedData and onSocketCamCanceled callbacks of helper.open()
  void hideSocketCam() {
    setState(() => _showSocketCam = false);
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Center(
          child: ElevatedButton(
            onPressed: _triggerSocketCam,
            child: const Text('Scan'),
          ),
        ),
        if (_showSocketCam)
          Positioned(
            right: 16,
            bottom: 16,
            width: 300,
            height: 300,
            child: SocketCamView(device: widget.socketCamDevice),
          ),
      ],
    );
  }
}
```

## JavaScript

```javascript
import { Platform, StyleSheet, View } from 'react-native';
import { SocketCamViewContainer, Trigger } from 'react-native-capture';
// Your own native component bridging your Android custom SocketCam view (see Requirements)
import RNSocketCamCustomViewManager from './RNSocketCamCustomViewManager';

// rootCapture, socketCamDevice, openSocketCamView and the CaptureHelper callbacks
// are the same as in the full screen sample

<View style={styles.socketCamSection}>
  <SocketCamViewContainer
    openSocketCamView={openSocketCamView}
    triggerType={Trigger.Start}
    clientOrDeviceHandle={rootCapture.clientOrDeviceHandle}
    socketCamCapture={rootCapture}
    socketCamDevice={socketCamDevice}
    handleSetSocketCamEnabled={() => {}}
    // iOS: SocketCam is rendered inline with this style instead of a full screen modal
    socketCamCustomStyle={styles.socketCamView}
    // Android: SocketCam is rendered by your own native view and activity
    androidSocketCamCustomView={
      Platform.OS === 'android' ? (
        <RNSocketCamCustomViewManager isScanContinuous={false} />
      ) : undefined
    }
  />
</View>

const styles = StyleSheet.create({
  socketCamSection: {
    flex: 1,
  },
  socketCamView: {
    // minimal size to display all SocketCam UI elements: 250 x 250
    width: 300,
    height: 300,
    alignSelf: 'center',
  },
});
```

## Sample code for SocketCam presented as a popover

The popover presentation is only available on iOS.

## Swift

```swift
var socketCamDevice: CaptureHelperDevice?
var mySocketCamViewController: UIViewController?

// The signature of the method to trigger SocketCam has now an extra return parameter: propertyObject. 
// It contains a dictionary that contains the SocketCam view controller that you can use as you wish in full screen, as a subview or a popover.

socketCamDevice.setTrigger(.start, withCompletionHandler: { result, propertyObject in
    DispatchQueue.main.async {
        if let anObject = propertyObject?.object,
           let dic = anObject as? [String: Any],
           let objectType = dic["SKTObjectType"] as? String, objectType == "SKTSocketCamViewControllerType",
           let socketCamViewController = dic["SKTSocketCamViewController"] as? UIViewController {
                let popOverVC = socketCamViewController.popoverPresentationController
                popOverVC?.delegate = self
                popOverVC?.sourceView = // a view of your chosing
                socketCamViewController.preferredContentSize = CGSize(width: myWidth, height: myHeight)
                socketCamViewController.modalPresentationStyle = .popover
                self.present(socketCamViewController, animated: true)
                // retain the socketcam view controller for the dismiss later
                self.mySocketCamViewController = socketCamViewController
        }
    }
})

extension MyViewController: CaptureHelperDeviceDecodedDataDelegate {
    // This delegate is called each time a decoded data is read from a scanner or SocketCam
    func didReceiveDecodedData(_ decodedData: SKTCaptureDecodedData?, fromDevice device: CaptureHelperDevice, withResult result:SKTResult) {
        print("--->>> didReceiveDecodedData for device: \(device.deviceInfo.deviceType)")
        if result == .E_NOERROR {
            let str = decodedData!.stringFromDecodedData()
            print("Decoded Data \(String(describing: str))")
        }
        DispatchQueue.main.async {
            // Dismiss and reset your socketCamViewController
            self.mySocketCamViewController?.dismiss(animated: true, completion: {
                self.mySocketCamViewController = nil
            })
        }
    }
}
```

## Configuring SocketCam close button

Depending on how you want to display SocketCam in your application, it may require to show or hide the close button of the SocketCam view controller. Ideally, you can execute this at the device arrival of a SocketCam device, whether it is C820 or C860. In order to do so, add a specific configuration as follow. By default, the button is shown.

> **Note**
>
> This configuration is only available on iOS. On Android, the default SocketCam view always shows its close button and <strong>SocketCamFragment</strong> never shows it.

## Swift

```swift
var socketCamDevice: CaptureHelperDevice?

extension MyViewController: CaptureHelperDevicePresenceDelegate {

  func didNotifyArrivalForDevice(_ device: CaptureHelperDevice, withResult result: SKTResult) {
      print("didNotifyArrivalForDevice: \(device.deviceInfo.name ?? "") - Result: \(result.rawValue)")
      if device.deviceInfo.deviceType = .socketCamC820 || device.deviceInfo.deviceType = .socketCamC860 {
          // handle SocketCam device arrival - Retains it to later trigger the camera scanning
          socketCamDevice = device

          let prop = SKTCaptureProperty()
          prop.id = SKTCapturePropertyID.configuration
          prop.type = .string
          prop.stringValue = "SocketCamCloseButton=enabled" /// to show the close button
          // OR
          prop.stringValue = "SocketCamCloseButton=disabled" /// to hide the close button
          self.captureHelper.setProperty(prop) { result, complete in
              print("SocketCam button result: \(result.rawValue)")
          }
      }
  }

}
```

## C#

```csharp
// iOS only
private CaptureHelperDevice _socketCamDevice;

async void CaptureDeviceArrival(object sender, CaptureHelper.DeviceArgs e)
{
    int type = e.CaptureDevice.GetDeviceInfo().Type;
    if (type == DeviceTypes.kSocketCamC820 || type == DeviceTypes.kSocketCamC860)
    {
        // handle SocketCam device arrival - Retains it to later trigger the camera scanning
        _socketCamDevice = e.CaptureDevice;

#if __IOS__
        var property = SktClassFactory.createCaptureProperty();
        property.ID = ICaptureProperty.PropId.kConfiguration;
        property.Type = ICaptureProperty.Types.kString;
        property.String = "SocketCamCloseButton=enabled"; // to show the close button
        // OR
        property.String = "SocketCamCloseButton=disabled"; // to hide the close button

        var result = await _capture.SetPropertyAsync(property);
        Console.WriteLine($"SocketCam close button result: {result.Result}");
#endif
    }
}
```

## JavaScript

```javascript
import {
  CaptureHelper,
  CaptureProperty,
  CapturePropertyIds,
  CapturePropertyTypes,
  SocketCamTypes,
} from 'react-native-capture';

const helper = new CaptureHelper({
  appInfo,

  onDeviceArrival: async (device) => {
    if (SocketCamTypes.indexOf(device.type) > -1) {
      // handle SocketCam device arrival - Retains it to later trigger the camera scanning
      setSocketCamDevice(device);

      const property = new CaptureProperty(
        CapturePropertyIds.Configuration,
        CapturePropertyTypes.String,
        'SocketCamCloseButton=enabled' // to show the close button
        // OR
        // 'SocketCamCloseButton=disabled' // to hide the close button
      );
      try {
        await helper.rootCapture.setProperty(property);
      } catch (err) {
        console.error('SocketCam close button error:', err?.code ?? err?.error?.code);
      }
    }
  },
});
```

## Triggering SocketCam in Continuous mode

The only difference between starting SocketCam as a single scan and a continous scan is the parameter of the **setTrigger** helper method: "Start" or "ContinuousScan".

Then you can store the decoded data results into an array that you can use after closing the SocketCam view.

## Java

```java
private DeviceClient mSocketCamDevice;
private final List<String> mResults = new ArrayList<>();

// Launches the SocketCam viewfinder, which keeps scanning barcodes until the user closes it
public void onScanButtonClicked(View view) {
    if (mSocketCamDevice == null) {
        return;
    }
    mSocketCamDevice.triggerContinuous(new PropertyCallback() {
        @Override
        public void onComplete(CaptureError error, Property property) {
            if (error != null) {
                Log.e(TAG, "SocketCam trigger failed: " + error.getMessage());
            }
        }
    });
}

// This handler is called each time a decoded data is read from a scanner or SocketCam
@Subscribe(threadMode = ThreadMode.MAIN)
public void onScan(DataEvent event) {
    DecodedData data = event.getData();
    if (data.result == DecodedData.RESULT_SUCCESS) {
        Log.d(TAG, "Decoded Data " + data.getString());
        // Add the decoded data result into your results list
        mResults.add(data.getString());
    } else {
        // The user closed the SocketCam viewfinder: the continuous scan session is over
        Log.d(TAG, "SocketCam session closed with " + mResults.size() + " results");
    }
}
```

## Kotlin

```kotlin
private var socketCamDevice: DeviceClient? = null
private val results = mutableListOf<String>()

// Launches the SocketCam viewfinder, which keeps scanning barcodes until the user closes it
fun onScanButtonClicked(view: View) {
    socketCamDevice?.triggerContinuous { error, _ ->
        if (error != null) {
            Log.e(TAG, "SocketCam trigger failed: ${error.message}")
        }
    }
}

// This handler is called each time a decoded data is read from a scanner or SocketCam
@Subscribe(threadMode = ThreadMode.MAIN)
fun onScan(event: DataEvent) {
    val data: DecodedData = event.data
    if (data.result == DecodedData.RESULT_SUCCESS) {
        Log.d(TAG, "Decoded Data ${data.string}")
        // Add the decoded data result into your results list
        results.add(data.string)
    } else {
        // The user closed the SocketCam viewfinder: the continuous scan session is over
        Log.d(TAG, "SocketCam session closed with ${results.size} results")
    }
}
```

## Swift

```swift
var socketCamDevice: CaptureHelperDevice?
var mySocketCamViewController: UIViewController?
var results: [String] = []

// The signature of the method to trigger SocketCam has now an extra return parameter: propertyObject. 
// It contains a dictionary that contains the SocketCam view controller that you can use as you wish in full screen, as a subview or a popover.

socketCamDevice.setTrigger(.continuousScan, withCompletionHandler: { result, propertyObject in
    DispatchQueue.main.async {
        if let anObject = propertyObject?.object,
           let dic = anObject as? [String: Any],
           let objectType = dic["SKTObjectType"] as? String, objectType == "SKTSocketCamViewControllerType",
           let socketCamViewController = dic["SKTSocketCamViewController"] as? UIViewController {
                socketCamViewController.modalPresentationStyle = .fullScreen
                self.present(socketCamViewController, animated: true)
                // retain the socketcam view controller for the dismissal later
                self.mySocketCamViewController = socketCamViewController
        }
    }
})

extension MyViewController: CaptureHelperDeviceDecodedDataDelegate {
    // This delegate is called each time a decoded data is read from a scanner or SocketCam
    func didReceiveDecodedData(_ decodedData: SKTCaptureDecodedData?, fromDevice device: CaptureHelperDevice, withResult result:SKTResult) {
        print("--->>> didReceiveDecodedData for device: \(device.deviceInfo.deviceType)")
        if result == .E_NOERROR {
            let str = decodedData!.stringFromDecodedData()
            print("Decoded Data \(String(describing: str))")

            // Add the decoded data result into your results array
            results.append(str)
        }
        DispatchQueue.main.async {
            // Dismiss and reset your socketCamViewController
            self.mySocketCamViewController?.dismiss(animated: true, completion: {
                self.mySocketCamViewController = nil
            })
        }
    }
}
```

## C#

```csharp
private CaptureHelperDevice _socketCamDevice;
private readonly List<string> _results = new();
#if __IOS__
private UIViewController _socketCamViewController;
#endif

private async void ButtonTriggerContinuous_Clicked(object sender, EventArgs e)
{
    var triggerResult = await _socketCamDevice.SetTriggerAsync(ICaptureProperty.Values.Trigger.kContinuousScan);

#if __IOS__
    // iOS: ResultObject contains a dictionary with the SocketCam view controller to present
    if (triggerResult.ResultObject is NSDictionary dictionary &&
        dictionary[NSObject.FromObject("SKTObjectType")] is NSString objectType &&
        objectType == "SKTSocketCamViewControllerType" &&
        dictionary[NSObject.FromObject("SKTSocketCamViewController")] is UIViewController socketCamViewController)
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            socketCamViewController.ModalPresentationStyle = UIModalPresentationStyle.FullScreen;
            Platform.GetCurrentUIViewController()?.PresentViewController(socketCamViewController, true, null);
            // retain the SocketCam view controller for the dismissal later
            _socketCamViewController = socketCamViewController;
        });
    }
#endif
}

// This event is fired each time a decoded data is read from a scanner or SocketCam
void CaptureDecodedData(object sender, CaptureHelper.DecodedDataArgs e)
{
    if (SktErrors.SKTSUCCESS(e.Result))
    {
        // Add the decoded data result into your results list
        _results.Add(e.DecodedData.DataToUTF8String);
    }
    else if (e.Result == SktErrors.ESKT_CANCEL)
    {
        // SocketCam has been closed by the user
#if __IOS__
        MainThread.BeginInvokeOnMainThread(() =>
        {
            // Dismiss and reset your SocketCam view controller
            _socketCamViewController?.DismissViewController(true, null);
            _socketCamViewController = null;
        });
#endif
    }
}
```

## Dart

```dart
import 'dart:io' show Platform;
import 'package:capturesdk_flutter/capturesdk.dart';

CaptureHelperDevice? socketCamDevice;
bool showSocketCam = false;
final List<String> results = <String>[];

Future<void> triggerSocketCamContinuous() async {
  final CaptureHelperDevice? device = socketCamDevice;
  if (device == null) {
    return;
  }
  try {
    // Android: the SDK opens its own full-screen camera Activity
    await device.setTrigger(Trigger.continuousScan);
    if (Platform.isIOS) {
      // iOS: mount a SocketCamView(device: device) widget in your layout.
      // The full-screen presentation is closed by the plugin on the first decoded data,
      // so continuous scanning uses the embedded view.
      setState(() => showSocketCam = true);
    }
  } on CaptureException catch (e) {
    debugPrint('SetTrigger error: ${e.code} ${e.message}');
  }
}

await helper.open(
  appInfo,
  // Called each time a decoded data is read from a scanner or SocketCam
  onDecodedData: (DecodedData data, CaptureHelperDevice device) {
    // Add the decoded data result into your results array
    setState(() => results.add(data.dataAsString()));
  },
  // Called when the user closes the SocketCam view
  onSocketCamCanceled: (CaptureHelperDevice device) {
    // Remove the SocketCamView widget and use your results
    setState(() => showSocketCam = false);
    debugPrint('Scanned ${results.length} barcodes');
  },
);
```

## JavaScript

```javascript
import { useEffect, useState } from 'react';
import { Button, View } from 'react-native';
import {
  CaptureHelper,
  SocketCamTypes,
  SocketCamViewContainer,
  Trigger,
} from 'react-native-capture';

const ContinuousScanScreen = () => {
  const [rootCapture, setRootCapture] = useState(null);
  const [socketCamDevice, setSocketCamDevice] = useState(null);
  const [openSocketCamView, setOpenSocketCamView] = useState(false);
  const [results, setResults] = useState([]);

  useEffect(() => {
    const helper = new CaptureHelper({
      appInfo,

      onDeviceArrival: (device) => {
        if (SocketCamTypes.indexOf(device.type) > -1) {
          setSocketCamDevice(device);
        }
      },

      // Called each time a decoded data is read from a scanner or SocketCam
      onDecodedData: (data, device) => {
        const decoded = String.fromCharCode(...data.data);
        console.log(`Decoded Data: ${decoded}`);
        // Add the decoded data result into your results array, the SocketCam view stays open
        setResults((previous) => [...previous, decoded]);
      },

      // Called when the user closes the SocketCam view with its close button
      onSocketCamCanceled: () => {
        setOpenSocketCamView(false);
      },
    });

    helper
      .open()
      .then(() => setRootCapture(helper.rootCapture))
      .catch(() => {});

    return () => {
      helper.close().catch(() => {});
    };
  }, []);

  return (
    <View style={{ flex: 1 }}>
      <Button
        title="Scan continuously"
        disabled={!socketCamDevice}
        onPress={() => setOpenSocketCamView(true)}
      />
      {rootCapture && (
        <SocketCamViewContainer
          openSocketCamView={openSocketCamView}
          triggerType={Trigger.ContinuousScan}
          clientOrDeviceHandle={rootCapture.clientOrDeviceHandle}
          socketCamCapture={rootCapture}
          socketCamDevice={socketCamDevice}
          handleSetSocketCamEnabled={() => {}}
        />
      )}
    </View>
  );
};
```

## Enabling SocketCam

On certain platforms, SocketCam needs to be enabled in order to be used. On Android, and on Windows with MAUI, the SocketCam **CaptureExtension** must also be started before enabling SocketCam. Flutter starts it in `CaptureHelper.open()` and React Native when **SocketCamViewContainer** is mounted.

## Java

```java
private CaptureClient mCaptureClient;
private CaptureExtension mCaptureExtension;

@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void onCaptureServiceConnectionStateChange(ConnectionStateEvent event) {
    ConnectionState state = event.getState();
    mCaptureClient = event.getClient();

    if (!state.hasError() && state.intValue() == ConnectionState.READY) {
        // Step 1: start the SocketCam CaptureExtension
        mCaptureExtension = new CaptureExtension.Builder()
                .setContext(getApplicationContext())
                .setClientHandle(mCaptureClient.getHandle())
                .setExtensionScope(ExtensionScope.LOCAL)
                .setListener(mExtensionListener)
                .build();
        mCaptureExtension.start();
    }
}

private final CaptureExtension.Listener mExtensionListener = new CaptureExtension.Listener() {
    @Override
    public void onExtensionStateChanged(ConnectionState connectionState) {
        if (connectionState.intValue() != ConnectionState.READY) {
            return;
        }
        // Step 2: retrieve the current status of SocketCam
        mCaptureClient.getSocketCamStatus(new PropertyCallback() {
            @Override
            public void onComplete(CaptureError getError, Property property) {
                if (getError == null && property.getByte() != SocketCamStatus.ENABLE) {
                    // set the status of SocketCam to enable
                    mCaptureClient.setSocketCamStatus(SocketCamStatus.ENABLE, new PropertyCallback() {
                        @Override
                        public void onComplete(CaptureError setError, Property property) {
                            Log.d(TAG, "SocketCam enabled " + (setError == null ? "successfully" : "failed: " + setError.getMessage()));
                        }
                    });
                }
            }
        });
    }

    @Override
    public void onError(CaptureError error) {
        Log.e(TAG, "SocketCam extension error: " + error.getMessage());
    }
};

// set the status of SocketCam to disable
mCaptureClient.setSocketCamStatus(SocketCamStatus.DISABLE, new PropertyCallback() {
    @Override
    public void onComplete(CaptureError setError, Property property) {
        Log.d(TAG, "SocketCam disabled " + (setError == null ? "successfully" : "failed: " + setError.getMessage()));
    }
});

@Override
protected void onDestroy() {
    super.onDestroy();
    // stop the SocketCam CaptureExtension when the application terminates
    if (mCaptureExtension != null) {
        mCaptureExtension.stop();
    }
}
```

## Kotlin

```kotlin
private var captureClient: CaptureClient? = null
private var captureExtension: CaptureExtension? = null

@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
fun onCaptureServiceConnectionStateChange(event: ConnectionStateEvent) {
    val state: ConnectionState = event.state
    val client: CaptureClient = event.client
    captureClient = client

    if (!state.hasError() && state.intValue() == ConnectionState.READY) {
        // Step 1: start the SocketCam CaptureExtension
        captureExtension = CaptureExtension.Builder()
            .setContext(applicationContext)
            .setClientHandle(client.handle)
            .setExtensionScope(ExtensionScope.LOCAL)
            .setListener(extensionListener)
            .build()
        captureExtension?.start()
    }
}

private val extensionListener = object : CaptureExtension.Listener {
    override fun onExtensionStateChanged(connectionState: ConnectionState) {
        if (connectionState.intValue() != ConnectionState.READY) return
        // Step 2: retrieve the current status of SocketCam
        captureClient?.getSocketCamStatus { getError, property ->
            if (getError == null && property?.byte != SocketCamStatus.ENABLE) {
                // set the status of SocketCam to enable
                captureClient?.setSocketCamStatus(SocketCamStatus.ENABLE) { setError, _ ->
                    Log.d(TAG, "SocketCam enabled ${if (setError == null) "successfully" else "failed: ${setError.message}"}")
                }
            }
        }
    }

    override fun onError(error: CaptureError) {
        Log.e(TAG, "SocketCam extension error: ${error.message}")
    }
}

// set the status of SocketCam to disable
captureClient?.setSocketCamStatus(SocketCamStatus.DISABLE) { setError, _ ->
    Log.d(TAG, "SocketCam disabled ${if (setError == null) "successfully" else "failed: ${setError.message}"}")
}

override fun onDestroy() {
    super.onDestroy()
    // stop the SocketCam CaptureExtension when the application terminates
    captureExtension?.stop()
}
```

## Swift

```swift
// On iOS, SocketCam is enabled by default
```

## C#

```csharp
private CaptureHelper _capture = new CaptureHelper();
private CaptureExtension _captureExtension; // Android and Windows only

private async Task OpenCaptureAsync(string appId, string developerId, string appKey)
{
    long result = await _capture.OpenAsync(appId, developerId, appKey);
    if (!SktErrors.SKTSUCCESS(result))
    {
        return;
    }

#if __ANDROID__
    // Android: start the CaptureExtension to gain access to the SocketCam device
    _captureExtension = new CaptureExtension(Android.App.Application.Context, _capture.GetHandle());
    _captureExtension.Start();
#elif WINDOWS
    // Windows: the context must be the MAUI Window hosting your page and the AppId must start with "windows:"
    _captureExtension = new CaptureExtension(Window, _capture.GetHandle(), appId, developerId, appKey);
    await _captureExtension.Start();
#endif

    // retrieve the current status of SocketCam
    var getStatus = await _capture.GetSocketCamStatusAsync();
    if (SktErrors.SKTSUCCESS(getStatus.Result) && getStatus.Status == CaptureHelper.SocketCamStatus.Disable)
    {
        // set the status of SocketCam to enable
        var setResult = await _capture.SetSocketCamStatusAsync(CaptureHelper.SocketCamStatus.Enable);
        Console.WriteLine($"SocketCam enabled returned {setResult.Result}");
    }
}
```

## Dart

```dart
final CaptureHelper helper = CaptureHelper();
// ... once helper.open() has completed

try {
  // retrieve the current status of SocketCam
  final dynamic status = await helper.getSocketCamEnabled();
  if (status == SocketCam.disable) {
    // set the status of SocketCam to enable
    await helper.setSocketCamEnabled(enabled: SocketCam.enable);
    debugPrint('SocketCam enabled');
  }
} on CaptureException catch (e) {
  debugPrint('SocketCam status error: ${e.code} ${e.message}');
}

// set the status of SocketCam to disable
try {
  await helper.setSocketCamEnabled(enabled: SocketCam.disable);
  debugPrint('SocketCam disabled');
} on CaptureException catch (e) {
  debugPrint('SocketCam status error: ${e.code} ${e.message}');
}
```

## JavaScript

```javascript
import { SocketCam } from 'react-native-capture';

// Android: SocketCamViewContainer must already be mounted (see Requirements)
try {
  // retrieve the current status of SocketCam
  const status = await helper.getSocketCamEnabled();
  if (status === SocketCam.Disable) {
    // set the status of SocketCam to enable - onDeviceArrival is called with the SocketCam device
    await helper.setSocketCamEnabled(true);
  }
} catch (err) {
  console.error('SocketCam enable error:', err?.code ?? err?.error?.code);
}

// set the status of SocketCam to disable - onDeviceRemoval is called with the SocketCam device
try {
  await helper.setSocketCamEnabled(false);
} catch (err) {
  console.error('SocketCam disable error:', err?.code ?? err?.error?.code);
}
```