How to interpret NetworkReachabilityFlags in Xamar

2019-07-30 09:45发布

问题:

I'm using NetworkReachability to figure out the connectivity status of my app:

NetworkReachability(this.currentHostUrl);
remoteHostReachability.SetNotification(this.ReachabilityChanged);
remoteHostReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault);

The callback method looks like this:

void ReachabilityChanged(NetworkReachabilityFlags flags)
{
    this.reachable = (flags & NetworkReachabilityFlags.Reachable) > 0;
    UIHelpers.GetAppDelegate().UpdateConnectivityToast(this.reachable);
}

Now if I switch to airplane mode, the callback gets called immediately and the flags parameter is 0. Then, shortly after it triggers again and the flags are

ConnectionRequired|IsWWAN|Reachable|TransientConnection

If I turn airplane mode off, I get another 0 and then afterwards

Reachable

If I turn WiFi off and 3G kicks in, the result is:

IsWWAN|Reachable|TransientConnection

It seems like checking for Reachable alone is not enough. But what's the logic here? What do ConnectionRequired and TransientConnection mean?

回答1:

If there is ConnectionRequired present, then there is actually no connectivity, even though Reachable is present so it's something like

bool connectionAvailable = (flags.HasFlag(Reachable) && !flags.HasFlags(ConnectionRequired))


回答2:

Quoting the documentations:

ConnectionRequired: Reachable, but a connection must first be established.

TransientConnection: The host is reachable using a transient connection (PPP for example).

Xamarin API Doc and iOS Lib Doc

But you probably can do it like the following sample code:

https://github.com/xamarin/monotouch-samples/blob/master/ReachabilitySample/reachability.cs

It basically checks if Reachable && (!ConnectionRequired || IsWWAN).