Xamarin.Forms ポップアップの表示と Http通信

1.全体

GAEにSpring Boot アプリケーションを配置し、WebアプリとしてVuetifyを構成するとともに、クライアントアプリケーションをXamarin.Forms を利用して作成したい。

whole_eco_sys

XamarinプロジェクトをVisual Studio 2019 に作成、iOSのエミュレーターでアプリを動かすことが出来るようになったので、HTTP通信でGAEにデプロイしたAPIを呼び出し疎通確認を行い、アラートダイアログに結果をポップアップさせる。

2.準備

Viusal Studio2019 のXamarinプロジェクトのテンプレートで作成された、Aboutページのボタンに、API呼び出しの処理を仕込もう。

https://docs.microsoft.com/ja-jp/xamarin/xamarin-forms/app-fundamentals/navigation/pop-ups

Visual Studioのテンプレートプロジェクトでは、ボタンの処理は、ViewModelに実装されているが、ポップアップ表示用の、DisplayAlert()DisplayActionSheet() ともに、Pageクラスのメソッドになっているため、ViewModel側からそのままでは参照できない。

まず、ViewModel(AboutViewModel)側に、Pageを格納するプロパティを用意。

  1. public Page Page
  2. {
  3. get;
  4. set;
  5. }

AboutPage.xmal を見ると、以下にViewModelの参照を保持しているようなので、

  1. <ContentPage.BindingContext>
  2. <vm:AboutViewModel />
  3. </ContentPage.BindingContext>

AboutPage.xmal.cs のコンストラクタで参照を渡す。

  1. public AboutPage()
  2. {
  3. InitializeComponent();
  4.  
  5. if (this.BindingContext is AboutViewModel)
  6. {
  7. (this.BindingContext as AboutViewModel).Page = this;
  8. }
  9. }

3.APIの呼び出し

https://docs.microsoft.com/ja-jp/xamarin/xamarin-forms/data-cloud/consuming/rest

まずはシンプルに疎通させる。セキュリティやらは追って確認。

Aboutページのボタンが押されたら、XamarinのWebページに遷移するところを置き換え、hello APIを呼び出し、結果をポップアップ表示させる。

  1. public class AboutViewModel : BaseViewModel
  2. {
  3.  
  4. public AboutViewModel()
  5. {
  6. Title = "About";
  7.  
  8. OpenWebCommand = new Command(RestTest);
  9. }
  10.  
  11. private async void RestTest()
  12. {
  13. string uri = "https://favophrase.com/api/hello";
  14.  
  15. HttpClient client = new HttpClient();
  16. var response = await client.GetAsync(uri);
  17. if (response.IsSuccessStatusCode)
  18. {
  19. var content = await response.Content.ReadAsStringAsync();
  20. bool answer = await this.Page?.DisplayAlert("REST API hello.", content, "Yes", "No");
  21.  
  22. Debug.WriteLine("Answer: " + answer);
  23. }
  24. }
  25.  
  26. public ICommand OpenWebCommand { get; }
  27. public Page Page
  28. {
  29. get;
  30. set;
  31. }
  32. }

4.結果

シンプルなテストコードだが、上記の1つのコードが、Anroid、iPhone、UWPアプリのエミュレータ(UWPについては、実機だが)で想定通り機能した。なかなか感動的。

rest_android

rest_ios

rest_uwp

この辺は、あとで確認する。

https://www.xlsoft.com/jp/products/xamarin/web_services.html

https://docs.microsoft.com/ja-jp/xamarin/ios/app-fundamentals/ats

https://docs.microsoft.com/ja-jp/xamarin/xamarin-forms/data-cloud/authentication/rest

https://docs.microsoft.com/ja-jp/aspnet/core/mobile/native-mobile-backend?view=aspnetcore-2.2

https://developer.xamarin.com/samples/xamarin-forms/WebServices/TodoREST/


Follow me!

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です