我只在 UWP 上遇到这个问题
private void Button_OnClicked(object sender, EventArgs e)
{
var clientId = Constants.GoogleUWPClientID;
var clientSecret = Constants.GoogleUWPClientSecret;
var redirectUrl = Constants.GoogleUWPRedirectUrl;
var auth = new OAuth2Authenticator(
clientId: clientId,
clientSecret: clientSecret,
scope: Constants.GoogleScope,
authorizeUrl: new Uri(Constants.GoogleAuthorizeUrl),
accessTokenUrl: new Uri(Constants.GoogleAccessTokenUrl),
redirectUrl: new Uri(redirectUrl),
getUsernameAsync: null,
isUsingNativeUI: true
);
// Login Events
auth.Completed += AuthOnCompleted;
auth.Error += AuthOnError;
auth.IsLoadableRedirectUri = true;
AuthenticationState.Authenticator = auth;
var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
presenter.Login(auth);
}
我确实在 UWP 上初始化了 Xamarin.Auth
Xamarin.Forms.Forms.Init(e);
global::Xamarin.Auth.Presenters.UWP.AuthenticationConfiguration.Init();
这是 CompletedEvent 处理程序
private async void AuthOnCompleted(object sender, AuthenticatorCompletedEventArgs authenticatorCompletedEventArgs)
{
//var auth = sender as Xamarin.Auth.OAuth2Authenticator;
//auth.DoNotEscapeScope = true;
// We presented the UI, so it's up to us to dimiss it on iOS.
//DismissViewController(true, null);
if (authenticatorCompletedEventArgs.IsAuthenticated)
{
var request = new OAuth2Request("GET", new Uri(Constants.GoogleUserInfoUrl), null, authenticatorCompletedEventArgs.Account);
var response = await request.GetResponseAsync();
if (response != null)
{
var userJson = response.GetResponseText();
var user = JsonConvert.DeserializeObject<GoogleUser>(userJson);
//UserPicture = user.Picture;
//GivenName = user.GivenName;
//Email = user.Email;
}
}
else
{
// The user cancelled
//ErrorMessage = "Cancelled authentication !";
}
}
一旦我成功登录 AuthOnCompleted 就会成功启动,但一旦它结束(或遇到来自我对 Google API 的请求之一的 await GetResponseAsync),它就会完全刷新应用程序。
我的猜测是,这是因为我没有像在 Android 和 iOS 中那样处理 redirect-url 吗?
在官方文档中没有提到 UWP 所以我不确定我是否遗漏了什么
我真的一无所知,我错过了什么吗?
编辑 01
我找到了解决办法,但我确实担心它可能会产生后果。我确实使用NavigationCacheMode="Enabled"
而不是默认的“取消”。
一旦我离开它的上下文并转到另一个 ContentPage/Page/Frame,这基本上会保留实例的缓存版本。因为 UWP 中的导航不像 Xamarin 中那样发生,所以您必须指定frame.Navigate(typeof(targetPage),args)
以便您必须处理每个页面的缓存(我猜)
让我担心的是 MainPage 并通过使用 UWP 中的此设置以及LoadApplication(new SharedProj.App())
此设置何时会被任何后续ContentPages
可能会导致应用程序性能问题的继承?
要做一些测试来检查我的假设
<forms:WindowsPage
x:Class="AnonymousCheckerApp.UWP.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:forms="using:Xamarin.Forms.Platform.UWP"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:AnonymousCheckerApp.UWP"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
NavigationCacheMode="Enabled"
>