LoginSignup
0
3

More than 5 years have passed since last update.

Xamarin.Forms ネットワークに接続可能か調べる

Last updated at Posted at 2017-01-31

やりたい事

Xamarin.Formsでネットワークに接続可能か判定する(もちろんクロスプラットフォームで)
※2017/01/31 現在Androidは動作しませんでした(情報提供お願いします...)

ライブラリを導入する

NuGetを利用して Connectivity Plugin for Xamarin and Windowsを追加する.

スクリーンショット 2017-01-31 19.26.19.png

コード

CheckNetworkConnectionPage.cs
using System;
using System.Collections.Generic;
using Plugin.Connectivity;
using Xamarin.Forms;

namespace XamarinSamples
{
    public partial class CheckNetworkConnectionPage : ContentPage
    {
        public CheckNetworkConnectionPage()
        {
            InitializeComponent();
            CrossConnectivity.Current.ConnectivityTypeChanged += Current_ConnectivityTypeChanged;
        }

        private async void Current_ConnectivityTypeChanged(object sender, Plugin.Connectivity.Abstractions.ConnectivityTypeChangedEventArgs e)
        {
            if (!e.IsConnected)
            {
                await DisplayAlert("Error", "Check for your connection.", "OK");
            }
            else {
                await DisplayAlert("Success", "Network is Available.", "OK");
            }
        }

        protected async override void OnAppearing()
        {
            base.OnAppearing();

            if (!CrossConnectivity.Current.IsConnected)
            {
                System.Diagnostics.Debug.WriteLine("connected");
                await DisplayAlert("Error", "Check for your connection", "OK");
            }
            else {
                await DisplayAlert("Success", "Network is Available.", "OK");
            }
        }
    }
}

動作確認

iOS

スクリーンショット 2017-01-31 19.30.04.png

Android

スクリーンショット 2017-01-31 19.44.17.png

しょぼん

0
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3