Search code examples
iosionic-frameworkgetusermediacapacitor

undefined is not an object (evalution 'navigation.mediaDevices.getUserMedia')


I want to open a camera scanner and below is code that working properly in android but in ios getting an error

TypeError: undefined is not an object (evalution 'navigation.mediaDevices.getUserMedia')

here is the full tutorial links https://devdactic.com/pwa-qr-scanner-ionic/ A small help is much appreciated

async startScan() {
  // Not working on iOS standalone mode!
  const stream = await navigator.mediaDevices.getUserMedia({
    video: { facingMode: 'environment' }
  });
 
  this.videoElement.srcObject = stream;
  // Required for Safari
  this.videoElement.setAttribute('playsinline', true);
 
  this.loading = await this.loadingCtrl.create({});
  await this.loading.present();
 
  this.videoElement.play();
  requestAnimationFrame(this.scan.bind(this));
}
 
async scan() {
  if (this.videoElement.readyState === this.videoElement.HAVE_ENOUGH_DATA) {
    if (this.loading) {
      await this.loading.dismiss();
      this.loading = null;
      this.scanActive = true;
    }
 
    this.canvasElement.height = this.videoElement.videoHeight;
    this.canvasElement.width = this.videoElement.videoWidth;
 
    this.canvasContext.drawImage(
      this.videoElement,
      0,
      0,
      this.canvasElement.width,
      this.canvasElement.height
    );
    const imageData = this.canvasContext.getImageData(
      0,
      0,
      this.canvasElement.width,
      this.canvasElement.height
    );
    const code = jsQR(imageData.data, imageData.width, imageData.height, {
      inversionAttempts: 'dontInvert'
    });
 
    if (code) {
      this.scanActive = false;
      this.scanResult = code.data;
      this.showQrToast();
    } else {
      if (this.scanActive) {
        requestAnimationFrame(this.scan.bind(this));
      }
    }
  } else {
    requestAnimationFrame(this.scan.bind(this));
  }
}

Solution

  • getUserMedia was not available on WKWebView on iOS 14.4 and older when using a custom scheme to load content, which Capacitor uses. Apple made getUserMedia available on iOS 14.5 and newer when using custom schemes and in a previous 14.x version if using https.

    To make it work, it’s required to add camera and/or microphone usage descriptions in the Info.plist (depending on the features you are using)