Search code examples
javascriptiosiphonesafaricamera

Accessing the camera in iOS Safari on an iPhone


I have Single Page Webapp (SPA) that verifies the users as part of the signup process. Part of the verification is to capture a selfie of the user. To this end, I've implemented a version of the following code to get the camera input into a video element on the webpage, from which I can then sample images into a canvas.

navigator.mediaDevices.getUserMedia({ video: true, audio: false })
    .then(localMediaStream => {
      if ('srcObject' in video) {
        video.srcObject = localMediaStream;
      } else {
        video.src = window.URL.createObjectURL(localMediaStream);
      }
      video.play();
    })
    .catch(err => {
      console.error(`Not available!!!!`, err);
    });

This code is based on an example by Wes Bos, from his JavaScript30 course (#19 Unreal Webcam Fun). You can try it out here.

This code appears to work fine on most browsers, with the major exception of Apple Safari on iOS on an iPhone (example: iPhone 12 Pro, iOS 14.7.1). On the iPhone I get the first frame of the camera image captured and there after, the video element displays a black square.

Oddly, it works fine on an iPad (example: iPad Pro (11-inch), iOS 14.7.1), but not on any iPhone that I've tried.

I've seen a lot of discussion here on StackOverflow and elsewhere describing similar issues, but I'm yet to find a definitive answer, or better yet, a solution.

Does anybody have any idea?

Cheers, S t u a r t .


Solution

  • I posted this question on other services and eventually received a response a user named Ravavyr through a separate Discord channel. The response pointed me to this article which provided an answer.

    https://leemartin.dev/hello-webrtc-on-safari-11-e8bcb5335295

    It appears that iOS Safari needs some more configuration to make it work.

    The CodePen linked from the original post has been updated to include the changes that make it work.

    // Fix for iOS Safari from https://leemartin.dev/hello-webrtc-on-safari-11-e8bcb5335295
    video.setAttribute('autoplay', '');
    video.setAttribute('muted', '');
    video.setAttribute('playsinline', '')
    

    I hope this helps future readers.