问题描述
我有一个页面,其中包含一个代码,该代码可从设备获取当前位置并使用此代码根据该位置加载其他内容:
I have a page that contains a code that gets the current location from the device and load other stuff based on the location with this code:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction);
} else {
// Make API call to the GeoIP services
}
它可以在我测试过的所有android设备上使用,但在iOS和macOS上却无法使用. if
和 else
都没有.似乎停留在获取当前位置上.
It works on all android devices that I tested, but on iOS and macOS, it’s not working. Neither if
nor else
. Seems like it stuck at getting the current location.
有帮助吗?
推荐答案
如果iOS和macOS不允许用户或(如果系统不信任您),iOS和macOS不会为您提供用户的位置.所以:
iOS and macOS doesn't give you the user's location if they don't allow it or if the system can not trust you. So:
它可以与您提供的确切代码配合使用,仅在主机(即原点)使用 https 的情况下.这是由于您对以下答案的评论而导致权限警报未显示的原因.
It works with the exact code you provided ONLY IF the host (aka the origin) is using https. That is the cause of permission alert not showing up due to your comment to an answer below.
请记住,如果您不使用 https ,它将停留约一分钟,然后返回有关身份验证失败的错误.使用错误进行检查:
Remember if you not use https, it will be stuck for about a minute and then returns an error about authentication failure. Use error to check that:
navigator.geolocation.getCurrentPosition(success, error, options)
它将告诉您以下信息:
提示:您可以在请求该位置以跳过等待过程后刷新页面.但是不要忘记在检查器中检查保留日志选项.
Tip: You can refresh the page after you requested the location to skip the waiting process. But don't forget to check the Preserve Log option in the inspector.
如果您使用的是 https ,然后检查Safari的位置设置(可能已以某种方式设置为OFF),则可以在此处进行更改:设置>隐私>位置服务> Safari.这不是默认选项,但是也许您不小心更改了它.因此,如果这是问题,请不必担心用户.如果您使用的是Chrome或任何其他第三方浏览器,请转到其设置并检查位置信息.默认情况下它不存在,并且仅在位置至少要一次时显示.
If you are using https, then check your location settings for Safari, which might have been set to OFF somehow, you can change it here: Settings > Privacy > Location Services > Safari. This is not the default option, but maybe you changed it accidentally. So don't worry about the users if this was the issue. And if you use Chrome or any other third party browsers, head to its settings and check for location access. It's not there by default and appears only if location wanted at least once.
如果您要使用 webView
在应用程序内加载网络,请确保将位置权限说明添加到info.plist 文件.根据需要添加 NSLocationWhenInUseUsageDescription
与 NSLocationAlwaysUsageDescription
与 NSLocationUsageDescription
.
If you are about to load your web inside an app using webView
, make sure to add location permission descriptions to the info.plist file. Add NSLocationWhenInUseUsageDescription
versus NSLocationAlwaysUsageDescription
versus NSLocationUsageDescription
as your needs.
出于完整性考虑,在iOS13上,您无法始终获得
权限.但这不是重点,重点是您必须之前获得必需的权限,然后才能从GPS获取位置,否则根本无法正常工作.
For the sake of completeness, on iOS13, you can not get always
permission. But this is not the point here and the point is you have to get the required permissions sometime before you need to get the location from GPS or it is not going to work at all.
这篇关于JS中的getCurrentPosition在iOS上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!