2017-10-28 1 views
0

私のアプリケーションにxamarin.formsを使用しています。これは、ユーザーがFacebookを介してログインすることができます。私はアプリにログアウトボタンを追加してログインページに戻りましたが、ログアウトボタンを押さずにアプリを終了すると、ログインページでアプリが再開し、ログインの詳細を毎回入力し続けることに気がつきました彼らはアプリケーションを再オープンする必要があります)。ユーザーがアプリケーションを閉じて再オープンしたときにログインしたままにする方法はありますか?この上の任意のガイダンスは理解されるであろう。..ログアウトをクリックしない限り、xamarin.formsアプリにユーザーをログインさせ続ける

がアップします

public App() 
     { 
      InitializeComponent(); 
      MainPage = new NavigationPage(new MainPage()); 
     } 

     public async static Task NavigateToSMS() 
     { 
      await App.Current.MainPage.Navigation.PushAsync(new SMS()); 
     } 

     public static void NavigateToProfile() 
     { 
      App.Current.MainPage = (new InvalidLogin()); 
     } 
     public static void NavigateToVerified() 
     { 
      App.Current.MainPage = (new Profile()); 
     } 

     protected override void OnStart() 
     { 
      // Handle when your app starts 
     } 

     protected override void OnSleep() 
     { 
      // Handle when your app sleeps 
     } 

     protected override void OnResume() 
     { 
      // Handle when your app sleeps 
     } 

FacebookRender

[assembly: ExportRenderer(typeof(Login), typeof(LoyaltyWorx.Droid.FacebookRender))] 
namespace LoyaltyWorx.Droid 
{ 

    public class FacebookRender : PageRenderer 
    { 
     public FacebookRender() 
     { 

      String error; 
      var activity = this.Context as Activity; 

      var auth = new OAuth2Authenticator(
       clientId: "", 
       scope: "email", 
       authorizeUrl: new Uri("https://www.facebook.com/dialog/oauth/"), 
       redirectUrl: new Uri("https://www.facebook.com/connect/login_success.html") 
       ); 

      auth.Completed += async (sender, eventArgs) => 
       { 
        try 
        { 
         if (eventArgs.IsAuthenticated) 
         { 
          await AccountStore.Create().SaveAsync(eventArgs.Account, "FacebookProviderKey"); 

          var accessToken = eventArgs.Account.Properties["access_token"].ToString(); 
          var expiresIn = Convert.ToDouble(eventArgs.Account.Properties["expires_in"]); 
          var expiryDate = DateTime.Now + TimeSpan.FromSeconds(expiresIn); 

          var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me?fields=email,first_name,last_name,gender,picture"), null, eventArgs.Account); 
          var response = await request.GetResponseAsync(); 
          var obj = JObject.Parse(response.GetResponseText()); 

          var id = obj["id"].ToString().Replace("\"", ""); 
          var name = obj["first_name"].ToString().Replace("\"", ""); 
          var surname = obj["last_name"].ToString().Replace("\"", ""); 
          var gender = obj["gender"].ToString().Replace("\"", ""); 
          var email = obj["email"].ToString().Replace("\"", ""); 

          Customer.Customers cust = new Customer.Customers(); 
          cust.Number = ""; 
          cust.Name = name; 
          cust.Surname = surname; 
          cust.Address = "sample"; 
          cust.Email = email; 
          cust.City = "DBN"; 
          cust.Region = "KZN"; 
          cust.Country = "SA"; 
          cust.MobilePhone = " "; 
          cust.DOB = DateTime.Now; 
          cust.Phone = " "; 
          cust.Credentials = new Customer.Credentials(); 
          cust.Credentials.Authenticated = true; 
          cust.Credentials.SecretKey = "73fnfdbjfdj"; 
          cust.DeviceToken = GcmService.RegistrationID; 


          CustomerService service = new CustomerService(); 
          Settings.Token = await service.AddCustomer(cust); 
          if (Settings.MobileNo == null || Settings.MobileNo == " ") 
          { 
           await App.NavigateToSMS(); 

          } 
          else 
          { 
           App.NavigateToVerified(); 
          } 
         } 
         else 
         { 
          App.NavigateToProfile(); 
         } 
        } 
        catch(Exception ex) 
        { 
         error = ex.Message; 
        } 
       }; 
      activity.StartActivity(auth.GetUI(activity)); 
     } 





    } 
} 

ページ(メインページは私のログインページです)App.csユーザーがサインインした後

namespace LoyaltyWorx 
{ 
    [XamlCompilation(XamlCompilationOptions.Compile)] 
    public partial class Profile : MasterDetailPage 
    { 
     public List<MasterPageItem> menuList { get; set; } 
     public Profile() 
     { 
      InitializeComponent(); 
      this.lblMessage.Text = Settings.Name + " " + Settings.Surname; 
      menuList = new List<MasterPageItem>(); 
      var page1 = new MasterPageItem() { Title = "Home", Icon = "home.png", TargetType = typeof(Page1) }; 
      var page2 = new MasterPageItem() { Title = "Cards", Icon = "card.png", TargetType = typeof(Cards) }; 
      var page3 = new MasterPageItem() { Title = "Transactions", Icon = "settings.png", TargetType = typeof(Transactions) }; 
      var page4 = new MasterPageItem() { Title = "My Profile", Icon = "profile.png", TargetType = typeof(UpdateProfile) }; 
      var page5 = new MasterPageItem() { Title = "Log out", Icon = "signout.png", TargetType = typeof(MainPage) }; 



      menuList.Add(page1); 
      menuList.Add(page2); 
      menuList.Add(page3); 
      menuList.Add(page4); 
      menuList.Add(page5); 


      navigationDrawerList.ItemsSource = menuList; 
      Detail = new NavigationPage((Page)Activator.CreateInstance(typeof(Page1))); 

     } 
     private void OnMenuItemSelected(object sender, SelectedItemChangedEventArgs e) 
     { 
      var item = (MasterPageItem)e.SelectedItem; 
      Type page = item.TargetType; 

      Detail = new NavigationPage((Page)Activator.CreateInstance(page)); 
      IsPresented = false; 
     } 

    } 
} 

セッティングクラス:ユーザーの詳細

public static class Settings 
    { 
     public static string Token; 
     public static int CustId; 
     public static string Name; 
     public static string Surname; 
     public static string Email; 
     public static string MobileNo; 
     public static string PhoneNo; 


    } 

App.csログイン店は - あなたがMainPageをロードしているすべてのアプリケーションの起動時に

public App() 
     { 
      App.Current.Properties["UserDetail"] = Settings.Token; 
      InitializeComponent(); 
      var isLoggedIn = Current.Properties.ContainsKey("UserDetail"); 
      if (!isLoggedIn) 
      { 
       MainPage = new NavigationPage(new MainPage()); 
      } 
      else 
      { 
       App.Current.MainPage = (new Profile()); 
      } 

     } 

答えて

0

を更新します。条件付きで最初のページを読み込む必要があります。

Xamarin.Formsは、アプリケーションのローカルストレージにキー値のデータを格納するApplication.Current.Propertiesを実装しています。ログイン時に

IsLoggedInのようないくつかのキーにアプリケーションのローカルストレージに成功したログイン、ストア "真の" 値に

次のようにアプリケーションの起動(App.csで

Application.Current.Properties ["IsLoggedIn"] = Boolean.TrueString; 

をログアウトオン)

public App() 
{ 
    InitializeComponent(); 
    bool isLoggedIn = Current.Properties.ContainsKey("IsLoggedIn") ? Convert.ToBoolean(Current.Properties["IsLoggedIn"]) : false; 
    if (!isLoggedIn) 
    { 
     //Load if Not Logged In 
     MainPage = new NavigationPage(new MainPage()); 
    } 
    else 
    { 
     //Load if Logged In 
     MainPage = new NavigationPage(new YourPageToLoadIfUserIsLoggedIn()); 
    } 
} 

ログアウトするときにIsLoggedInローカルストレージキーにFalseの値を格納し、ナビゲーションスタックをクリアしてMainPageをロードします。

Application.Current.Properties ["IsLoggedIn"] = Boolean.FalseString; 

ユーザーの詳細保存:

Jsonにそれをシリアル化、設定クラスのオブジェクトの値を格納する(Nuget Package)文字列オブジェクトを、いくつかの他のキー、たとえば、Application.Current.PropertiesUserDetailに保管してください。 このデータが必要な場合は、ローカルストレージから取り出して、そのデータを廃止して使用してください。

ストア:App.Current.Properties["UserDetail"] = JsonConvert.SerializeObject(Settings); を取得:いくつかのキーがストレージに存在するかどうSettings userData = JsonConvert.DeserializeObject<Settings>(App.Current.Properti‌​es["UserDetail"]);

EDIT

Current.Properties.ContainsKeyはちょうどチェックします。値が存在するかどうかはチェックしません。任意のキー値にアクセスする前に、そのキーが存在するかどうかを確認する必要があります。

スタティッククラスはシリアル化できないため、そのクラスのシングルトンインスタンスを作成してから、そのシングルトンインスタンスにアクセスしてシリアル化する必要があります。

これは役に立ちます。

+0

ありがとうございました。これを試してみましたが、ユーザーがログインしたときに正しいページが開きます。ユーザーのログイン情報に基づいて表示されるはずのデータは表示されません。これをどうすれば解決できますか?ユーザーがFacebook経由でログインすると、これらの詳細を取得してアプリで使用するために保存する設定クラスがあります。私の編集を確認してください、私はそこにそれを追加しました。 –

+0

私の編集した答えを見てください。 – MilanG

+0

私は戻るボタンを押すと保存されたデータは保持されますが、アプリケーションが完全に閉じられたときに、すべてのデータが移動して再びログインページを入力するとアプリを再入力します –

0

Settings Pluginを使用してこの問題を解決しました。完璧に動作します!

関連する問題