我正在处理一个cordova app
,它的纬度和经度必须为locate the user
。使用地理定位插件,它在安卓设备上运行良好,但在iOS
中会显示一条请求用户许可的警报。当我使用模拟器时,我收到了以下警告信息:
Users/user/Library/Developer/CoreSimulator/Devices/783A2EFD-2976-448C-8E4E-841C985D337D/data/Containers/Bundle/Application/EFC846BB-4BA3-465C-BD44-575582E649FC/app_name.app/www/index.html would like to use your current location.
我看到过关于这个问题的话题,比如:这个和这个,但提供的解决方案都不适合我
这是cordova的示例页面:
<!DOCTYPE html>
<html>
<head>
<title>Device Properties Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'Altitude: ' + position.coords.altitude + '<br />' +
'Accuracy: ' + position.coords.accuracy + '<br />' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '<br />' +
'Heading: ' + position.coords.heading + '<br />' +
'Speed: ' + position.coords.speed + '<br />' +
'Timestamp: ' + position.timestamp + '<br />';
}
function onError(error) {
alert('code: ' + error.code + 'n' +
'message: ' + error.message + 'n');
}
</script>
</head>
<body>
<p id="geolocation">Finding geolocation...</p>
</body>
有什么方法可以更改警报的文本或禁用此警报吗?
-编辑---
我已经找到了问题的根源。我删除了地理定位插件并添加了好几次,因为当我添加插件时,我还没有像其他插件一样找到一个名为geolocation plugin
的文件夹。即使是cordova_plugin.js
文件也不包含任何关于地理定位插件的数据。现在我又安装了这个插件,它可以工作了。
与原问题中的"编辑"相同,我不得不删除旧版本的地理定位插件并添加新版本。然后我不得不删除/添加Cordova iOS平台。只有到那时,我才能将NSLocationWhenInUseUsageDescription
添加到.plist文件中,正如DaveAlden在成功的回答中提到的那样。
首先,删除/添加地理定位插件:
cordova plugin rm org.apache.cordova.geolocation
cordova plugin add org.apache.cordova.geolocation
第二,删除/添加iOS平台:
cordova platform rm ios
cordova platform add ios
最后,将NSLocationWhenInUseUsageDescription
添加到.plist。打开/platforms/ios/{project}/{project}-Info.plist
并添加以下内容:
<key>NSLocationWhenInUseUsageDescription</key>
<string>[App Name] would like to access your location when running and displayed.</string>
有关NSLocationWhenInUseUsageDescription
与NSLocationAlwaysUsageDescription
与NSLocationUsageDescription
的详细信息,请参阅此iOS开发人员库链接。
- 确保"cordova.js"文件存在于您的根文件夹中,只需将此js文件包含在您访问此位置的.html文件中即可解决此问题。不需要任何花哨的东西。如果这个js文件丢失,navigator.geolocation将调用基于浏览器的HTML5对象,从而发出奇怪的警报
您不能在模拟器或设备上禁用请求消息,但您可以通过在项目的.plist.中添加属性来自定义它
对于iOS 8,如果你的应用程序请求在后台使用位置的权限,你需要以下密钥(将字符串值设置为你喜欢的任何值):
<key>NSLocationAlwaysUsageDescription</key>
<string>My app requires constant access to your location, even when the screen is off.</string>
如果您的应用程序仅在前台使用位置,则添加以下密钥:
<key>NSLocationWhenInUseUsageDescription</key>
<string>My app requires access to your location when the screen is on and the app is displayed.</string>
对于旧版本的iOS(<=7),您需要使用NSLocationUsageDescription