iOS是否可以通过Reachability检测wifi网络连接(没有互联网连接)

时间:2018-01-26 09:59:58

标签: ios swift networking reachability network-connection

如果用户连接到没有活动互联网连接的wifi网络,如何检测场景?

可以通过互联网连接检测wifi连接。 我从这里下载了样品。

https://github.com/xamarin/ios-samples/tree/master/ReachabilitySample

它在Xamarin编码,但我也对swift或objective c中的解决方案感兴趣。

// Reachability.cs

using System;
using System.Net;
using SystemConfiguration;

using CoreFoundation;

namespace Reachability {
    public enum NetworkStatus {
        NotReachable,
        ReachableViaCarrierDataNetwork,
        ReachableViaWiFiNetwork
    }

    public static class Reachability {
        public static string HostName = "www.google.com";

        public static bool IsReachableWithoutRequiringConnection (NetworkReachabilityFlags flags)
        {
            // Is it reachable with the current network configuration?
            bool isReachable = (flags & NetworkReachabilityFlags.Reachable) != 0;

            // Do we need a connection to reach it?
            bool noConnectionRequired = (flags & NetworkReachabilityFlags.ConnectionRequired) == 0
                || (flags & NetworkReachabilityFlags.IsWWAN) != 0;

            return isReachable && noConnectionRequired;
        }

        // Is the host reachable with the current network configuration
        public static bool IsHostReachable (string host)
        {
            if (string.IsNullOrEmpty (host))
                return false;

            using (var r = new NetworkReachability (host)) {
                NetworkReachabilityFlags flags;

                if (r.TryGetFlags (out flags))
                    return IsReachableWithoutRequiringConnection (flags);
            }
            return false;
        }

        //
        // Raised every time there is an interesting reachable event,
        // we do not even pass the info as to what changed, and
        // we lump all three status we probe into one
        //
        public static event EventHandler ReachabilityChanged;

        static void OnChange (NetworkReachabilityFlags flags)
        {
            ReachabilityChanged?.Invoke (null, EventArgs.Empty);
        }

        //
        // Returns true if it is possible to reach the AdHoc WiFi network
        // and optionally provides extra network reachability flags as the
        // out parameter
        //
        static NetworkReachability adHocWiFiNetworkReachability;

        public static bool IsAdHocWiFiNetworkAvailable (out NetworkReachabilityFlags flags)
        {
            if (adHocWiFiNetworkReachability == null) {
                var ipAddress = new IPAddress (new byte[] { 169, 254, 0, 0 });
                adHocWiFiNetworkReachability = new NetworkReachability (ipAddress.MapToIPv6 ());
                adHocWiFiNetworkReachability.SetNotification (OnChange);
                adHocWiFiNetworkReachability.Schedule (CFRunLoop.Current, CFRunLoop.ModeDefault);
            }

            return adHocWiFiNetworkReachability.TryGetFlags (out flags) && IsReachableWithoutRequiringConnection (flags);
        }

        static NetworkReachability defaultRouteReachability;

        static bool IsNetworkAvailable (out NetworkReachabilityFlags flags)
        {
            if (defaultRouteReachability == null) {
                var ipAddress = new IPAddress (0);
                defaultRouteReachability = new NetworkReachability (ipAddress.MapToIPv6 ());
                defaultRouteReachability.SetNotification (OnChange);
                defaultRouteReachability.Schedule (CFRunLoop.Current, CFRunLoop.ModeDefault);
            }
            return defaultRouteReachability.TryGetFlags (out flags) && IsReachableWithoutRequiringConnection (flags);
        }

        static NetworkReachability remoteHostReachability;

        public static NetworkStatus RemoteHostStatus ()
        {
            NetworkReachabilityFlags flags;
            bool reachable;

            if (remoteHostReachability == null) {
                remoteHostReachability = new NetworkReachability (HostName);

                // Need to probe before we queue, or we wont get any meaningful values
                // this only happens when you create NetworkReachability from a hostname
                reachable = remoteHostReachability.TryGetFlags (out flags);

                remoteHostReachability.SetNotification (OnChange);
                remoteHostReachability.Schedule (CFRunLoop.Current, CFRunLoop.ModeDefault);
            } else {
                reachable = remoteHostReachability.TryGetFlags (out flags);
            }

            if (!reachable)
                return NetworkStatus.NotReachable;

            if (!IsReachableWithoutRequiringConnection (flags))
                return NetworkStatus.NotReachable;

            return (flags & NetworkReachabilityFlags.IsWWAN) != 0 ?
                NetworkStatus.ReachableViaCarrierDataNetwork : NetworkStatus.ReachableViaWiFiNetwork;
        }

        public static NetworkStatus InternetConnectionStatus ()
        {
            NetworkReachabilityFlags flags;
            bool defaultNetworkAvailable = IsNetworkAvailable (out flags);

            if (defaultNetworkAvailable && ((flags & NetworkReachabilityFlags.IsDirect) != 0))
                return NetworkStatus.NotReachable;

            if ((flags & NetworkReachabilityFlags.IsWWAN) != 0)
                return NetworkStatus.ReachableViaCarrierDataNetwork;

            if (flags == 0)
                return NetworkStatus.NotReachable;

            return NetworkStatus.ReachableViaWiFiNetwork;
        }

        public static NetworkStatus LocalWifiConnectionStatus ()
        {
            NetworkReachabilityFlags flags;
            if (IsAdHocWiFiNetworkAvailable (out flags))
            if ((flags & NetworkReachabilityFlags.IsDirect) != 0)
                return NetworkStatus.ReachableViaWiFiNetwork;

            return NetworkStatus.NotReachable;
        }
    }
}

// MainViewController.cs

using System;
using Foundation;
using UIKit;

namespace Reachability {
    public partial class MainViewController : UITableViewController {
        const string ReachabilityTableCellIdentifier = "ReachabilityTableCell";

        UIImage imageCarrier, imageWiFi, imageStop;
        NetworkStatus remoteHostStatus, internetStatus, localWifiStatus;

        public MainViewController (IntPtr handle) : base (handle)
        {
        }

        public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();
            UpdateStatus (null, null);
            Reachability.ReachabilityChanged += UpdateStatus;

            imageCarrier = UIImage.FromFile ("WWAN5.png");
            imageWiFi = UIImage.FromFile ("Airport.png");
            imageStop = UIImage.FromFile ("stop-32.png");

            TableView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
            TableView.RowHeight = 44f;
            TableView.SeparatorStyle = UITableViewCellSeparatorStyle.None;
            TableView.SectionHeaderHeight = 28f;
            TableView.ScrollEnabled = false;
        }

        public override NSIndexPath WillSelectRow (UITableView tableView, NSIndexPath indexPath)
        {
            return null;
        }

        public override nint RowsInSection (UITableView tableView, nint section)
        {
            return 1;
        }

        public override nint NumberOfSections (UITableView tableView)
        {
            return 3;
        }

        public override string TitleForHeader (UITableView tableView, nint section)
        {
            switch (section) {
            case 0:
                return Reachability.HostName;
            case 1:
                return "Access to internet hosts";
            case 2:
                return "Access to Local Bonjour Hosts";
            default:
                return "Unknown";
            }
        }

        public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
        {
            var cell = tableView.DequeueReusableCell (ReachabilityTableCellIdentifier);
            if (cell == null) {
                cell = new UITableViewCell (UITableViewCellStyle.Default, ReachabilityTableCellIdentifier);
                var label = cell.TextLabel;
                label.Font = UIFont.SystemFontOfSize (12f);
                label.TextColor = UIColor.DarkGray;
                label.TextAlignment = UITextAlignment.Left;
            }

            string text = string.Empty;
            UIImage image = null;
            switch (indexPath.Section) {
            case 0:
                switch (remoteHostStatus) {
                case NetworkStatus.NotReachable:
                    text = "Cannot connect to remote host";
                    image = imageStop;
                    break;
                case NetworkStatus.ReachableViaCarrierDataNetwork:
                    text = "Reachable via data carrier network";
                    image = imageCarrier;
                    break;
                case NetworkStatus.ReachableViaWiFiNetwork:
                    text = "Reachable via WiFi network";
                    image = imageWiFi;
                    break;
                }
                break;
            case 1:
                switch (internetStatus) {
                case NetworkStatus.NotReachable:
                    text = "Access not available";
                    image = imageStop;
                    break;
                case NetworkStatus.ReachableViaCarrierDataNetwork:
                    text = "Available via data carrier network";
                    image = imageCarrier;
                    break;
                case NetworkStatus.ReachableViaWiFiNetwork:
                    text = "Available via WiFi network";
                    image = imageWiFi;
                    break;
                }
                break;
            case 2:
                switch (localWifiStatus) {
                case NetworkStatus.NotReachable:
                    text = "Access not available";
                    image = imageStop;
                    break;
                case NetworkStatus.ReachableViaWiFiNetwork:
                    text = "Available via WiFi network";
                    image = imageWiFi;
                    break;
                }
                break;
            }
            cell.TextLabel.Text = text;
            cell.ImageView.Image = image;
            return cell;
        }

        void UpdateStatus (object sender, EventArgs e)
        {
            remoteHostStatus = Reachability.RemoteHostStatus ();
            internetStatus = Reachability.InternetConnectionStatus ();
            localWifiStatus = Reachability.LocalWifiConnectionStatus ();
            TableView.ReloadData ();
        }
    }
}

0 个答案:

没有答案