developer9969
developer9969

Reputation: 5236

Detaching Connectivity Changes Xamarin Forms

I am using Xamarin.Essentials to handle connectivity changes, it all works on android

However I have noticed that in iOS it didnt work, I debugged and noticed that

  1. sliding down the screen in iOS Physical device

  2. Put the phone in Plane Mode and remove wifi

  3. Sleep event fired and removed connectivity

    //App.Xaml
    
    protected override void OnSleep()
    {
        Connectivity.ConnectivityChanged -= OnConnectivityChanged;
    }
    
    protected override void OnStart()
    {
        Connectivity.ConnectivityChanged += OnConnectivityChanged;
    }
    
    
    
    protected override void OnResume()
    {
         Connectivity.ConnectivityChanged += OnConnectivityChanged;
    }
    

if I comment out

 Connectivity.ConnectivityChanged -= OnConnectivityChanged; 

it all works. Am I missing the obvious?

WHere I am supposed to detach the connectivity?

Upvotes: 0

Views: 431

Answers (1)

Leo Zhu
Leo Zhu

Reputation: 15021

This is because the Forms lifecycle is somewhat different from the declarative lifecycle approach of native platform, and you can do this directly in the native ios lifecycle.

in your ios project 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)
    {
        //do some thing
    }

You could refer to the lefecycle.

Note: on iOS 13 (and later),you need write them to SceneDelegate as well.

Upvotes: 1

Related Questions