用于Internet检查的ConnectivityChanged事件在Xamarin ios中无法正常工作

aoyhnmkz  于 2022-12-07  发布在  iOS
关注(0)|答案(1)|浏览(110)

我想在运行时检查互联网访问,使用Xamarin Essential我试图实现相同的。但事件没有正确触发。目前,它是击中时,第一次连接丢失。没有响应时,再次在线。请帮助我在这方面。在Android的工作正常,问题是在iOS。
这是我代码。

BaseViewModel: INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public bool IsNotConnected { get; set; }
    public BaseViewModel()
    {
        Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
        IsNotConnected = Connectivity.NetworkAccess != NetworkAccess.Internet;
    }

    ~BaseViewModel()
    {
        Connectivity.ConnectivityChanged -= Connectivity_ConnectivityChanged;
    }

    void Connectivity_ConnectivityChanged(object sender, ConnectivityChangedEventArgs e)
    {
        IsNotConnected = e.NetworkAccess != NetworkAccess.Internet;
    }
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
a11xaf1n

a11xaf1n1#

Forms生命周期与本机平台的声明性生命周期方法有些不同,您可以直接在本机iOS生命周期中这样做。
AppDelegate.cs中:

public override void OnActivated(UIApplication application)
    {
        Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
    }

 public override void DidEnterBackground(UIApplication uiApplication)
    {
        Connectivity.ConnectivityChanged -= Connectivity_ConnectivityChanged;
    }

 private void Connectivity_ConnectivityChanged(object sender, ConnectivityChangedEventArgs e)
    {
        //...
    }

您也可以检查此生命周期。
在iOS 13(及更高版本)上,您还需要将它们写入SceneDelegate

相关问题