一次显示xamarin表单的多个权限

时间:2018-11-16 08:06:19

标签: c# xamarin.forms

我正在为Android和IOS创建Xamarin Form PCL项目。 是否可以在屏幕上一次显示多个权限?我的应用程序正在使用“位置,存储和摄像头”权限。从我当前的代码来看,这就像在使用相机之前一样,在不同页面上逐一显示权限弹出窗口,然后显示相机权限弹出窗口。据我所知,我的应用需要三个权限,因此我想为所有三个权限显示一个弹出窗口。 下面是我的存储权限代码。

public static async Task<dynamic> CheckStoragePermission()
    {
        var result = "";
        try
        {
            var Storagestatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Plugin.Permissions.Abstractions.Permission.Storage);
            if (Storagestatus != PermissionStatus.Granted)
            {
                await Utils.CheckPermissions(Plugin.Permissions.Abstractions.Permission.Storage);
            }
        }
        catch (Exception ex)
        {
            error(ex.Message, Convert.ToString(ex.InnerException), ex.Source, ex.StackTrace);
        }
        return result;
    }

希望有人以前以xamarin的形式进行此操作,谢谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您可以尝试使用以下代码一次请求多个权限:

private async void Button_Clicked(object sender, EventArgs e)
    {
        await GetPermissions();
    }


public static async Task<bool> GetPermissions()
    {
        bool permissionsGranted = true;

        var permissionsStartList = new List<Permission>()
        {
            Permission.Location,
            Permission.LocationAlways,
            Permission.LocationWhenInUse,
            Permission.Storage,
            Permission.Camera
        };

        var permissionsNeededList = new List<Permission>();
        try
        {
            foreach (var permission in permissionsStartList)
            {
                var status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
                if (status != PermissionStatus.Granted)
                {
                    permissionsNeededList.Add(permission);
                }
            }
        }
        catch (Exception ex)
        {
        }

        var results = await CrossPermissions.Current.RequestPermissionsAsync(permissionsNeededList.ToArray());

        try
        {
            foreach (var permission in permissionsNeededList)
            {
                var status = PermissionStatus.Unknown;
                //Best practice to always check that the key exists
                if (results.ContainsKey(permission))
                    status = results[permission];
                if (status == PermissionStatus.Granted || status == PermissionStatus.Unknown)
                {
                    permissionsGranted = true;
                }
                else
                {
                    permissionsGranted = false;
                    break;
                }
            }
        }
        catch (Exception ex)
        {
        }
        return permissionsGranted;
    }