简体   繁体   English

Xamarin Forms:如何在 Xamarin ios 应用程序中检查 GPS 是打开还是关闭?

[英]Xamarin Forms: How to check if GPS is on or off in Xamarin ios app?

Whenever I am opening my app I need to check the GPS is on or off.每当我打开我的应用程序时,我都需要检查 GPS 是否打开。 If the GPS is off, I need to redirect the user to the location settings page.如果 GPS 关闭,我需要将用户重定向到位置设置页面。 I have done the android part using the dependency service like below.我已经使用如下依赖服务完成了 android 部分。

ILocSettings ILoc设置

public interface ILocSettings
{
    void OpenSettings();

    bool isGpsAvailable();
}

Android implementation安卓实现

[assembly: Dependency(typeof(LocationShare))]
namespace Projectname.Droid.Services 
{
    public class LocationShare : ILocSettings
    {
        public bool isGpsAvailable()
        {
            bool value = false;
            Android.Locations.LocationManager manager = (Android.Locations.LocationManager)Android.App.Application.Context.GetSystemService(Android.Content.Context.LocationService);
            if (!manager.IsProviderEnabled(Android.Locations.LocationManager.GpsProvider))
            {
                //gps disable
                value = false;
            }
            else
            {
                //Gps enable
                value = true;
            }
            return value;
        }

        public void OpenSettings()
        {
            Intent intent = new Android.Content.Intent(Android.Provider.Settings.ActionLocat‌​ionSourceSettings);
            intent.AddFlags(ActivityFlags.NewTask);
            Android.App.Application.Context.StartActivity(intent);
        }
    }
}

Finally from the shared project called like below:最后来自如下调用的共享项目:

//For checking the GPS Status
bool gpsStatus = DependencyService.Get<ILocSettings>().isGpsAvailable();
//For opening the location settings 
DependencyService.Get<ILocSettings>().OpenSettings();

For ios how I can I do the same features?对于 ios,我如何才能执行相同的功能? I tried like below:我试过如下:

[assembly: Dependency(typeof(LocationShare))]
namespace Projectname.iOS.Serivces
{
    class LocationShare : ILocSettings
    {
        public bool isGpsAvailable()
        {
            //how to check the GPS is on or off here
        }

        public void OpenSettings()
        {
            UIApplication.SharedApplication.OpenUrl(new NSUrl(UIApplication.OpenSettingsUrlString));
        }
    }
}

Location settings page opening on ios simulators, but don't know how to check the GPS status.在 ios 模拟器上打开位置设置页面,但不知道如何查看 GPS 状态。

Update1更新1

I have tried the CLLocationManager code and it is not working as expected.我已经尝试了CLLocationManager代码,但它没有按预期工作。 It returns true always even if the location is off or on.即使位置关闭或打开,它也始终返回 true。

OpenSettings() function code ( UIApplication.SharedApplication.OpenUrl(new NSUrl(UIApplication.OpenSettingsUrlString)); ) is also not working as expected, it is redirecting to some other page , I need to open the location settings page if the GPS is off. OpenSettings() 函数代码( UIApplication.SharedApplication.OpenUrl(new NSUrl(UIApplication.OpenSettingsUrlString)); )也没有按预期工作,它正在重定向到其他页面,如果 GPS 关闭,我需要打开位置设置页面.

Also, I am requesting location permission like below:另外,我正在请求位置许可,如下所示:

var status = await Permissions.RequestAsync<Permissions.LocationAlways>();

In android , location permission is asking, but in ios, no permissions are asking.android 中,请求位置权限,但在 ios 中,没有请求权限。

Update2更新2

I have tried the new codes and getting false value always as GPS status.我已经尝试了新的代码并且总是将错误值作为 GPS 状态。 I have added all the location permission on the info.plist like below:我在info.plist上添加了所有位置权限,如下所示:

在此处输入图片说明

But location permission is not asking when running the app (not even a single time).但是在运行应用程序时不会询问位置权限(甚至一次)。 I have tried Permissions.LocationWhenInUse instead of Permissions.LocationAlways , but no luck.我试过Permissions.LocationWhenInUse而不是Permissions.LocationAlways ,但没有运气。

Update 3更新 3

Following is my complete flow for checking location permission, checking GPS status, and open settings.以下是我检查位置权限、检查 GPS 状态和打开设置的完整流程。 The permission status value is always Disabled .权限状态值始终为Disabled

//Requesting permission like below:
var status = await Permissions.RequestAsync<Permissions.LocationAlways>();
if (status == PermissionStatus.Granted)
{
    //Then checking the GPS state like below
    bool gpsStatus = DependencyService.Get<ILocSettings>().isGpsAvailable();
    if (!gpsStatus)
    {
        //show a message to user here for sharing the GPS
        //If user granted GPS Sharing, opening the location settings page like below:
        DependencyService.Get<ILocSettings>().OpenSettings();
    }
}

I have tried the below 2 codes for requesting or checking permission.我已经尝试了以下 2 个代码来请求或检查权限。 In both cases, the status value is Disabled.在这两种情况下,状态值都是 Disabled。 If I uninstall the app and reinstall it again, getting the same status and not showing any permission pop-up window.如果我卸载应用程序并重新安装它,得到相同的状态并且不显示任何权限弹出窗口。

var status = await Permissions.RequestAsync<Permissions.LocationAlways>();
var status = await Permissions.CheckStatusAsync<Permissions.LocationWhenInUse>();

Unlike the Android system, iOS can set the GPS switch separately, and can only get the status of whether the location service is turned on.安卓系统不同,iOS可以单独设置GPS开关,只能获取位置服务是否开启的状态。 The rest of the specific positioning method will be left to the iOS system to choose.剩下的具体定位方法就留给iOS系统去选择了。

At the beginning, we need to have a look at the status of location in iOS:一开始,我们需要看看iOS中location的状态:

CLAuthorizationStatus Enum CLAuthorizationStatus 枚举

在此处输入图片说明

UIApplicationOpenSettingsURLString : Used to create a URL that you can pass to the openURL: method. UIApplicationOpenSettingsURLString :用于创建可以传递给 openURL: 方法的 URL。 When you open the URL built from this string, the system launches the Settings app and displays the app's custom settings, if it has any.当您打开根据该字符串构建的 URL 时,系统会启动“设置”应用程序并显示该应用程序的自定义设置(如果有)。

From now, iOS only support this way to displays the app's custom settings.从现在开始,iOS 只支持这种方式来显示应用程序的自定义设置。 There are two helpful discussion, you could have a look.有两个有用的讨论,你可以看看。 How to jump to system setting's location service on iOS10? iOS10如何跳转到系统设置的定位服务? and Open Location Settings Not working in ios 11 Objective c?打开位置设置在 ios 11 Objective c 中不起作用? . .

If it is redirecting to some other page as follows:如果它重定向到其他页面,如下所示:

在此处输入图片说明

That means your app not do any settings about the location service after installing the app .这意味着您的应用程序在安装应用程序后不会对位置服务进行任何设置。 Therefore , you not need to open the setting page, because it will not show the location service bellow the setting page of your app.因此,您无需打开设置页面,因为它不会在您的应用程序设置页面下方显示位置服务。 Now the CLAuthorizationStatus should be NotDetermined .现在CLAuthorizationStatus应该是NotDetermined You could use CLLocationManager.RequestWhenInUseAuthorization to request the permission, the popup window of location service will show for customer to choose inside the app.您可以使用CLLocationManager.RequestWhenInUseAuthorization来请求权限,位置服务的弹出窗口将显示给客户在应用程序内选择。

在此处输入图片说明

If customer select Don't Allow first time, that means next time opening the app to check the location service that will show Denied status.如果客户第一次选择不允许,这意味着下次打开应用程序检查将显示拒绝状态的位置服务。 Now you will need to use UIApplicationOpenSettingsURLString to open the settings page and will see the location service inside the app's custom settings list.现在您需要使用UIApplicationOpenSettingsURLString打开设置页面,并会在应用的自定义设置列表中看到位置服务。

At last, the final code of LocationShare is as follows:最后LocationShare的最终代码如下:

public class LocationShare : ILocSettings
{
    public bool isGpsAvailable()
    {
        bool value = false;

        if ( CLLocationManager.LocationServicesEnabled )
        {
            if(CLLocationManager.Status == CLAuthorizationStatus.Authorized || CLLocationManager.Status == CLAuthorizationStatus.AuthorizedAlways || CLLocationManager.Status == CLAuthorizationStatus.AuthorizedWhenInUse)
            {//enable
                value = true;
            }
            else if (CLLocationManager.Status == CLAuthorizationStatus.Denied)
            {
                value = false;
                OpenSettings();
            }
            else{
                value = false;
                RequestRuntime();
            }
        }
        else
        {
            //location service false
            value = false;
            //ask user to open system setting page to turn on it manually.
        }
        return value;
    }


    public void RequestRuntime()
    {
        CLLocationManager cLLocationManager = new CLLocationManager();
        cLLocationManager.RequestWhenInUseAuthorization();
    }

    public void OpenSettings()
    {

        UIApplication.SharedApplication.OpenUrl(new NSUrl(UIApplication.OpenSettingsUrlString));
    }
}

Similarly , if CLAuthorizationStatus is Denied (the same as status == PermissionStatus.Unknown in Forms), the following code will not work in Forms.同样,如果CLAuthorizationStatusDenied (与 Forms 中的status == PermissionStatus.Unknown相同),以下代码在 Forms 中将不起作用。

var status = await Permissions.RequestAsync<Permissions.LocationAlways>();

It only works when CLAuthorizationStatus is NotDetermined .它仅在CLAuthorizationStatusNotDeterminedNotDetermined And you'd better request Permissions.LocationWhenInUse instead of Permissions.LocationAlways , this should be the better recommanded option.并且您最好请求Permissions.LocationWhenInUse而不是Permissions.LocationAlways ,这应该是更好的推荐选项。

============================Update #2================================ ============================更新#2================== ==============

I have modified the above code, and you will see that if CLLocationManager.LocationServicesEnabled is false, we only can ask user to redirect to the system setting page to turn on the service manually.我修改了上面的代码,你会看到如果CLLocationManager.LocationServicesEnabled为false,我们只能要求用户重定向到系统设置页面手动开启服务。 Because from iOS 10, iOS not supports to navigate to system setting page from non-system app.因为从 iOS 10 开始,iOS 不支持从非系统应用程序导航到系统设置页面。

============================Update #3====================================== ============================更新#3================== ====================

If location service is enabled, when using UIApplication.SharedApplication.OpenUrl(new NSUrl(UIApplication.OpenSettingsUrlString));如果启用定位服务,当使用UIApplication.SharedApplication.OpenUrl(new NSUrl(UIApplication.OpenSettingsUrlString)); method you will see the similar screenshot as follows:方法你会看到类似的截图如下:

在此处输入图片说明

The Loaction option will show in the list. Loaction 选项将显示在列表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM