Ionic and Cordova ios deviceorientation

189 Views Asked by At

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"

2

There are 2 best solutions below

4
Q.u.a.n.g L. On BEST ANSWER

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);
  }
}
1
StackoverBlows On

You need to be using a plugin to target the native device orientation methods. Here are a few:

Cordova Plugin

Capacitor