If you are still in the process of determining if the device is running on iOS or not, I suggest following this method:
- Start by creating a folder named
helper
- Within this folder, create a file named either
platform.ts
or platform.js
- Inside this file, export the function
isIOS
:
export const isIOS = () => {
let platform = navigator?.userAgent || navigator?.platform || 'unknown'
return /iPhone|iPod|iPad/.test(platform)
}
The result will return true
if it detects an iPhone
, iPod
, or Ipad
, and false
otherwise.
You might be wondering why we need to check
navigator.userAgent || navigator.platform
. The reason being that while the latter used to be the default, it is now deprecated and may not be supported by some browsers in the future. The former option is more reliable.
You can find more information about the deprecation mentioned above here:
https://developer.mozilla.org/en-US/docs/Web/API/Navigator/platform#:~:text=Deprecated%3A%20This%20feature%20is%20no,be%20kept%20for%20compatibility%20purposes.
Examining userAgentData
, userAgent
, and platform
logs.
Upon using the function below, I obtained the following logs:
console.log({
userAgentData: navigator?.userAgentData?.platform,
userAgent: navigator?.userAgent,
platform: navigator?.platform,
})
{
"userAgentData": "",
"userAgent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1",
"platform": "MacIntel"
}
I tested this on my MacBook across different browsers and operating systems, and it worked consistently. Thus, as observed,
navigator?.userAgentData?.platform
does not yield any meaningful results.
Despite using React to call this function, no errors related to TypeScript were encountered.
Extra: Detecting Android Devices
In case you are curious about identifying whether the platform is Android, avoiding the approach of simply negating isIOS
is advised:
const isAndroid = !isIOS();
This method won't suffice because desktop devices could mistakenly be identified as running on Android.
To accurately assess for Android platforms, utilize the following code snippet:
export const isAndroid = () => {
const ua = navigator.userAgent.toLowerCase() + navigator?.platform.toLowerCase();
const isAndroid = ua.indexOf("android") > -1;
return isAndroid;
}
The rationale behind checking both navigator.userAgent
and navigator?.platform
is to ensure compatibility with both older and newer browser versions.