如何检查用户是否已授予应用程序图片文件夹的权限?

How to check if user has granted app the permission for pictures folder?

我的 UWP 应用的清单已请求该权限。但是,似乎有时(可能自 Windows 1809 年起)不会自动授予。相反,用户需要从控制面板打开应用程序的高级选项并进行设置。

那么有没有办法检查应用程序是否有权限以通知用户?

这就是我的意思:设置 > 应用 > (点击应用) > 单击“高级选项”。另请注意,某些应用可能 不需要 任何权限,因此您可能看不到它们的任何权限。查看 MS 天气应用程序,它需要两个权限。

这是迄今为止我找到的最佳解决方案:

private async Task<StorageLibrary> TryAccessLibraryAsync(KnownLibraryId library)
{
    try
    {
        return await StorageLibrary.GetLibraryAsync(library);
    }
    catch (UnauthorizedAccessException)
    {
        //inform user about missing permission and ask to grant it
        MessageDialog requestPermissionDialog =
            new MessageDialog($"The app needs to access the {library}. " +
                       "Press OK to open system settings and give this app permission. " +
                       "If the app closes, please reopen it afterwards. " +
                       "If you Cancel, the app will have limited functionality only.");
        var okCommand = new UICommand("OK");
        requestPermissionDialog.Commands.Add(okCommand);
        var cancelCommand = new UICommand("Cancel");
        requestPermissionDialog.Commands.Add(cancelCommand);
        requestPermissionDialog.DefaultCommandIndex = 0;
        requestPermissionDialog.CancelCommandIndex = 1;

        var requestPermissionResult = await requestPermissionDialog.ShowAsync();
        if (requestPermissionResult == cancelCommand)
        {
            //user chose to Cancel, app will not have permission
            return null;
        }

        //open app settings to allow users to give us permission
        await Launcher.LaunchUriAsync(new Uri("ms-settings:appsfeatures-app"));

        //confirmation dialog to retry
        var confirmationDialog = new MessageDialog(
              $"Please give this app the {library} permission.");
        confirmationDialog.Commands.Add(okCommand);
        await confirmationDialog.ShowAsync();

        //retry
        return await TryAccessLibraryAsync(library);
    }
}

它首先尝试通过 KnownLibraryId 获取给定的库。如果用户删除了应用程序的权限,则它将失败并显示 UnauthorizedAccessException

现在我们向用户显示 MessageDialog 来解释问题并要求他授予应用程序权限。

如果用户按下 取消,该方法将 return null 因为用户没有授予我们权限。

否则,我们使用特殊的启动 URI ms-settings:appsfeatures-app(参见 docs)启动 设置,这会打开带有权限切换的应用程序高级设置页面.

现在有一个不幸的问题 - 我发现更改权限会强制关闭应用程序。我在第一个对话框中告知用户这个事实。以防将来发生这种变化,代码已经为这种替代方案做好了准备——显示一个新对话框,用户可以在更改权限时确认它,该方法将递归调用自身并尝试再次访问库。

当然,我会建议在应用程序因权限更改而关闭之前保存用户数据,以便在重新打开时,数据将保持完整,用户流量不会中断。

如果您真的依赖此权限来实现其功能,也可以在应用启动后立即调用此权限。这样你就知道你要么有访问权限,要么用户会在一开始就授予它,所以应用程序将被终止这一事实没有什么坏处。

更新:我发现这个问题很有趣所以我有 written a blogpost about it.