Search code examples
ioscordovaionic-frameworkcompassdevice-orientation

Ionic and Cordova ios deviceorientation


from cordova-ios v6 this code doesn't work. He worked with version 5 and work in Android OS. Do you have any idea why?

function watchOrientation(callback) {
    if ("ondeviceorientationabsolute" in window) {
        console.log("ondeviceorientationabsolute");
        window.addEventListener("deviceorientationabsolute", callback);
    } else if ("ondeviceorientation" in window) {
        console.log("ondeviceorientation");
        window.addEventListener("deviceorientation", callback);
    } else {
        console.log("none device orientation event");
    }

    return callback;
}

I have just log "ondeviceorientation"


Solution

  • On iOS, you must get the user permission first. Some idea:

    function watchOrientation() {
      if (isIOS) {
        DeviceOrientationEvent.requestPermission()
          .then((response) => {
            if (response === "granted") {
              window.addEventListener("deviceorientation", handler, true);
            } else {
              alert("has to be allowed!");
            }
          })
          .catch(() => alert("not supported"));
      } else {
        window.addEventListener("deviceorientationabsolute", handler, true);
      }
    }