-
-
Save Krumelur/49c5fa6ec3479cbda1e9 to your computer and use it in GitHub Desktop.
iOS Reachability
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using MonoTouch.CoreFoundation; | |
using MonoTouch.SystemConfiguration; | |
using Xamarin.Forms; | |
using System; | |
using WebServices.iOS; | |
using System.Threading.Tasks; | |
[assembly:Dependency(typeof(AppleConnectivityServiceImpl))] | |
namespace WebServices.iOS | |
{ | |
public class AppleConnectivityServiceImpl : IConnectivityService | |
{ | |
string currentHostUrl; | |
bool reachable = true; | |
NetworkReachability remoteHostReachability; | |
Action<bool> connectivityChanged; | |
public void CreateConnectivityWatchDog (Action<bool> connectivityChanged, string hostUrl) | |
{ | |
this.connectivityChanged = connectivityChanged; | |
if (string.IsNullOrWhiteSpace(hostUrl)) | |
{ | |
// See "Link-Local-Address": http://en.wikipedia.org/wiki/Link-local_address | |
hostUrl = "169.254.0.0"; | |
} | |
if (remoteHostReachability == null || hostUrl != currentHostUrl) | |
{ | |
if (remoteHostReachability != null) | |
{ | |
remoteHostReachability.Unschedule(CFRunLoop.Current, CFRunLoop.ModeDefault); | |
} | |
// Create new instance if host address changed. | |
currentHostUrl = hostUrl; | |
// Does not work with iOS 8.0.2. Used to work. | |
//remoteHostReachability = new NetworkReachability(currentHostUrl); // e.g. "http://www.google.com | |
// This works: | |
remoteHostReachability = new NetworkReachability(new IPAddress(0);) | |
remoteHostReachability.SetNotification(HandleReachabilityChanged); | |
remoteHostReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault); | |
} | |
// Trigger callback. | |
if (this.connectivityChanged != null) | |
{ | |
this.connectivityChanged (true); | |
} | |
} | |
private void HandleReachabilityChanged(NetworkReachabilityFlags flags) | |
{ | |
Console.WriteLine (flags); | |
var requiresConnection = (flags & NetworkReachabilityFlags.ConnectionRequired) > 0; | |
// It's reachable if Reachable flag is set and no connection is required. | |
reachable = !requiresConnection && (flags & NetworkReachabilityFlags.Reachable) > 0; | |
// Trigger callback. | |
if (this.connectivityChanged != null) | |
{ | |
this.connectivityChanged (reachable); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment