Skip to content

Instantly share code, notes, and snippets.

@MartinZikmund
Last active December 25, 2020 15:52
Show Gist options
  • Save MartinZikmund/694db493f8bc773df3b9aa8893c46875 to your computer and use it in GitHub Desktop.
Save MartinZikmund/694db493f8bc773df3b9aa8893c46875 to your computer and use it in GitHub Desktop.
Access library safely
private async Task<StorageLibrary> TryAccessLibraryAsync(KnownLibraryId library)
{
try
{
return await StorageLibrary.GetLibraryAsync(library);
}
catch (UnauthorizedAccessException)
{
//explain the issue
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, 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 " +
"in the Settings app which has now opened.");
confirmationDialog.Commands.Add(okCommand);
await confirmationDialog.ShowAsync();
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment