如何检查iOS或macOS上的活动Internet连接?

Bro*_*olf 1309 macos cocoa cocoa-touch reachability ios

我想查看我是否在iOS上使用Cocoa Touch库或使用Cocoa库在macOS 上建立了Internet连接.

我想出了一个方法,使用一个NSURL.我这样做的方式似乎有点不可靠(因为即使谷歌有一天会失败并依赖第三方看起来很糟糕),而且如果谷歌没有回应,我可以查看其他网站的回复,在我的应用程序中看起来似乎很浪费并且不必要的开销

- (BOOL) connectedToInternet
{
    NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
    return ( URLString != NULL ) ? YES : NO;
}
Run Code Online (Sandbox Code Playgroud)

我做得不好,(更不用说stringWithContentsOfURL在iOS 3.0和macOS 10.4中被弃用)如果是这样,有什么更好的方法来实现这一目标?

iwa*_*bed 1272

重要说明:此检查应始终异步执行.下面的大部分答案都是同步的,所以要小心,否则你会冻结你的应用程序.


迅速

1)通过CocoaPods或Carthage安装:https://github.com/ashleymills/Reachability.swift

2)通过闭包测试可达性

let reachability = Reachability()!

reachability.whenReachable = { reachability in
    if reachability.connection == .wifi {
        print("Reachable via WiFi")
    } else {
        print("Reachable via Cellular")
    }
}

reachability.whenUnreachable = { _ in
    print("Not reachable")
}

do {
    try reachability.startNotifier()
} catch {
    print("Unable to start notifier")
}
Run Code Online (Sandbox Code Playgroud)

Objective-C的

1)SystemConfiguration向项目添加框架,但不要担心将其包含在任何地方

2)添加托尼百万的版本Reachability.hReachability.m到项目(在这里找到:https://github.com/tonymillion/Reachability)

3)更新接口部分

#import "Reachability.h"

// Add this to the interface in the .m file of your view controller
@interface MyViewController ()
{
    Reachability *internetReachableFoo;
}
@end
Run Code Online (Sandbox Code Playgroud)

4)然后在您可以调用的视图控制器的.m文件中实现此方法

// Checks if we have an internet connection or not
- (void)testInternetConnection
{   
    internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];

    // Internet is reachable
    internetReachableFoo.reachableBlock = ^(Reachability*reach)
    {
        // Update the UI on the main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"Yayyy, we have the interwebs!");
        });
    };

    // Internet is not reachable
    internetReachableFoo.unreachableBlock = ^(Reachability*reach)
    {
        // Update the UI on the main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"Someone broke the internet :(");
        });
    };

    [internetReachableFoo startNotifier];
}
Run Code Online (Sandbox Code Playgroud)

重要说明:Reachability该类是项目中使用最多的类之一,因此您可能会遇到与其他项目的命名冲突.如果发生这种情况,您必须将其中一对Reachability.hReachability.m文件重命名为其他内容以解决问题.

注意:您使用的域名无关紧要.它只是测试任何域的网关.

  • @gonzobrains:您使用的域名无关紧要.它只是测试*any*域的网关. (4认同)
  • @KaanDedeoglu这只是一个例子,使用你想要的任何域名.它只是检查到互联网的网关,而不是域实际可用. (3认同)
  • 使用www.appleiphonecell.com而不是google.com - 这个网址是由apple创建的,正是出于这个原因. (2认同)
  • 现在(2018 年)使用 www.appleiphonecell.com 是一个糟糕的选择。现在它会重定向到 Apple.com,这是一个 > 40kB 的 html 文件。回到 google.com - 它只有 11kB。BTW google.com/m 大小相同,但据报道慢了 120 毫秒。 (2认同)

can*_*boy 308

我喜欢简单易懂.我这样做的方式是:

//Class.h
#import "Reachability.h"
#import <SystemConfiguration/SystemConfiguration.h>

- (BOOL)connected;

//Class.m
- (BOOL)connected
{
    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus networkStatus = [reachability currentReachabilityStatus];
    return networkStatus != NotReachable;
}
Run Code Online (Sandbox Code Playgroud)

然后,每当我想看看我是否有连接时,我都会使用它:

if (![self connected]) {
    // Not connected
} else {
    // Connected. Do some Internet stuff
}
Run Code Online (Sandbox Code Playgroud)

此方法不会等待更改的网络状态以执行操作.它只是在您要求时测试状态.

  • 对于那些像我对上面的代码所做的那样复制和粘贴的人。还要手动添加 SystemConfiguration.framework 否则您将收到链接错误。 (2认同)

And*_*mer 144

使用Apple的Reachability代码,我创建了一个函数,可以正确地检查这个,而不必包含任何类.

在项目中包含SystemConfiguration.framework.

做一些进口:

#import <sys/socket.h>
#import <netinet/in.h>
#import <SystemConfiguration/SystemConfiguration.h>
Run Code Online (Sandbox Code Playgroud)

现在只需调用此函数:

/*
Connectivity testing code pulled from Apple's Reachability Example: https://developer.apple.com/library/content/samplecode/Reachability
 */
+(BOOL)hasConnectivity {
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
    if (reachability != NULL) {
        //NetworkStatus retVal = NotReachable;
        SCNetworkReachabilityFlags flags;
        if (SCNetworkReachabilityGetFlags(reachability, &flags)) {
            if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
            {
                // If target host is not reachable
                return NO;
            }

            if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
            {
                // If target host is reachable and no connection is required
                //  then we'll assume (for now) that your on Wi-Fi
                return YES;
            }


            if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
                 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
            {
                // ... and the connection is on-demand (or on-traffic) if the
                //     calling application is using the CFSocketStream or higher APIs.

                if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
                {
                    // ... and no [user] intervention is needed
                    return YES;
                }
            }

            if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
            {
                // ... but WWAN connections are OK if the calling application
                //     is using the CFNetwork (CFSocketStream?) APIs.
                return YES;
            }
        }
    }

    return NO;
}
Run Code Online (Sandbox Code Playgroud)

它是iOS 5为您测试的.

  • 这会泄漏内存 - 需要使用CFRelease()释放'可读性'结构(对象,事物). (5认同)

Dan*_*ser 120

这曾经是正确的答案,但它现在已经过时,因为您应该订阅可达性通知.此方法同步检查:


您可以使用Apple的Reachability类.它还允许您检查是否启用了Wi-Fi:

Reachability* reachability = [Reachability sharedReachability];
[reachability setHostName:@"www.example.com"];    // Set your host name here
NetworkStatus remoteHostStatus = [reachability remoteHostStatus];

if (remoteHostStatus == NotReachable) { }
else if (remoteHostStatus == ReachableViaWiFiNetwork) { }
else if (remoteHostStatus == ReachableViaCarrierDataNetwork) { }
Run Code Online (Sandbox Code Playgroud)

SDK不提供Reachability类,而是Apple示例应用程序的一部分.只需下载它,并将Reachability.h/m复制到您的项目中.此外,您必须将SystemConfiguration框架添加到项目中.

  • 请参阅上面的评论,关于不使用这样的Reachability.在异步模式下使用它并订阅它发送的通知 - 不要. (6认同)

Eri*_*rik 81

这是一个非常简单的答案:

NSURL *scriptUrl = [NSURL URLWithString:@"http://www.google.com/m"];
NSData *data = [NSData dataWithContentsOfURL:scriptUrl];
if (data)
    NSLog(@"Device is connected to the Internet");
else
    NSLog(@"Device is not connected to the Internet");
Run Code Online (Sandbox Code Playgroud)

该URL应指向一个非常小的网站.我在这里使用谷歌的移动网站,但如果我有一个可靠的网络服务器,我会上传一个只包含一个字符的小文件,以获得最大速度.

如果检查设备是否以某种方式连接到Internet是您想要做的一切,我肯定建议使用这个简单的解决方案.如果您需要知道用户的连接方式,那么使用Reachability是可行的方法.

小心:这会在加载网站时短暂阻止你的线程.在我的情况下,这不是一个问题,但你应该考虑这一点(由Brad指出这一点).

  • 我真的很喜欢这个想法,但我会说99.999%的可靠性,同时保持较小的响应大小,请访问www.google.com/m这是google的移动视图. (10认同)
  • Apple文档建议不要这样做,因为它可以阻止慢速网络上的线程,可能导致应用程序在iOS中终止 (4认同)
  • 大声笑,我相信Google会感谢您建议人们将它们用作互联网检查资源. (3认同)

klc*_*r89 72

以下是我在我的应用程序中执行的操作:虽然200状态响应代码不保证任何内容,但它对我来说足够稳定.这不需要像这里发布的NSData答案一样多的加载,因为我只是检查HEAD响应.

SWIFT代码

func checkInternet(flag:Bool, completionHandler:(internet:Bool) -> Void)
{
    UIApplication.sharedApplication().networkActivityIndicatorVisible = true

    let url = NSURL(string: "http://www.google.com/")
    let request = NSMutableURLRequest(URL: url!)

    request.HTTPMethod = "HEAD"
    request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
    request.timeoutInterval = 10.0

    NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.mainQueue(), completionHandler:
    {(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in

        UIApplication.sharedApplication().networkActivityIndicatorVisible = false

        let rsp = response as! NSHTTPURLResponse?

        completionHandler(internet:rsp?.statusCode == 200)
    })
}

func yourMethod()
{
    self.checkInternet(false, completionHandler:
    {(internet:Bool) -> Void in

        if (internet)
        {
            // "Internet" aka Google URL reachable
        }
        else
        {
            // No "Internet" aka Google URL un-reachable
        }
    })
}
Run Code Online (Sandbox Code Playgroud)

Objective-C代码

typedef void(^connection)(BOOL);

- (void)checkInternet:(connection)block
{
    NSURL *url = [NSURL URLWithString:@"http://www.google.com/"];
    NSMutableURLRequest *headRequest = [NSMutableURLRequest requestWithURL:url];
    headRequest.HTTPMethod = @"HEAD";

    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    defaultConfigObject.timeoutIntervalForResource = 10.0;
    defaultConfigObject.requestCachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;

    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue: [NSOperationQueue mainQueue]];

    NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:headRequest
        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
    {
        if (!error && response)
        {
            block([(NSHTTPURLResponse *)response statusCode] == 200);
        }
    }];
    [dataTask resume];
}

- (void)yourMethod
{
    [self checkInternet:^(BOOL internet)
    {
         if (internet)
         {
             // "Internet" aka Google URL reachable
         }
         else
         {
             // No "Internet" aka Google URL un-reachable
         }
    }];
}
Run Code Online (Sandbox Code Playgroud)

  • 由于中国政府现在完全封锁google.com,截至2014年6月,这将在中国大陆失败.(google.cn虽然有效,但在中国大陆,没有baidu.com,没有互联网)可能更好地ping你需要与之通信的服务器. (9认同)
  • 请使用www.appleiphonecell.com - 苹果正是出于这个原因创建了这个网址. (4认同)
  • 似乎这是最快的方式 (3认同)
  • 警告:根据我的经验,此解决方案不会一直有效.在许多情况下,在花了它的甜蜜时间后,返回的响应是403.这个解决方案似乎很完美,但不能保证100%的结果. (3认同)

tea*_*bot 56

Apple提供示例代码以检查不同类型的网络可用性.或者,在iPhone开发人员食谱中有一个例子.

注意:有关使用Apple的可访问性代码,请参阅@KHG对此答案的评论.

  • 请注意,Apple的Reachability示例代码的新版本(09-08-09)是异步的. (7认同)

Ale*_*izi 47

你可以使用Reachability(这里有).

#import "Reachability.h"

- (BOOL)networkConnection {
    return [[Reachability reachabilityWithHostName:@"www.google.com"] currentReachabilityStatus];
}

if ([self networkConnection] == NotReachable) { /* No Network */ } else { /* Network */ } //Use ReachableViaWiFi / ReachableViaWWAN to get the type of connection.
Run Code Online (Sandbox Code Playgroud)


小智 39

Apple提供了一个示例应用程序,它正是如下:

可达性

  • 您应该注意,Reachability示例仅检测哪些接口处于活动状态,而不检测哪些接口与Internet的有效连接.即使Reachability报告一切准备就绪,应用程序也应该优雅地处理故障. (7认同)

Ben*_*oot 33

只有Reachability类已更新.您现在可以使用:

Reachability* reachability = [Reachability reachabilityWithHostName:@"www.apple.com"];
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];

if (remoteHostStatus == NotReachable) { NSLog(@"not reachable");}
else if (remoteHostStatus == ReachableViaWWAN) { NSLog(@"reachable via wwan");}
else if (remoteHostStatus == ReachableViaWiFi) { NSLog(@"reachable via wifi");}
Run Code Online (Sandbox Code Playgroud)


Ale*_*lex 27

关于iOS 5 Reachability的版本是darkseed/Reachability.h.不是我的!=)


JK *_*iho 25

这里有一个漂亮的,ARC和GCD使用的可达性现代化:

可达性


Bru*_*oga 22

如果您正在使用AFNetworking,则可以使用自己的实现来实现Internet可访问性状态.

最好的使用方法AFNetworking是对类进行子AFHTTPClient类化,并使用此类进行网络连接.

使用此方法的一个优点是,您可以blocks在可达性状态更改时使用设置所需的行为.假设我已经创建了一个单独的子类AFHTTPClient(如AFNetworking文档中的"Subclassing notes" 所述)BKHTTPClient,我会做类似的事情:

BKHTTPClient *httpClient = [BKHTTPClient sharedClient];
[httpClient setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
{
    if (status == AFNetworkReachabilityStatusNotReachable) 
    {
    // Not reachable
    }
    else
    {
        // Reachable
    }
}];
Run Code Online (Sandbox Code Playgroud)

您还可以使用AFNetworkReachabilityStatusReachableViaWWANAFNetworkReachabilityStatusReachableViaWiFi枚举检查Wi-Fi或WLAN连接(此处更多内容).


Fel*_*xyz 18

我在这个讨论中使用了代码,它似乎工作正常(阅读整个线程!).

我没有用各种可能的连接(如ad hoc Wi-Fi)对其进行详尽的测试.


Raj*_*han 14

非常简单....尝试以下步骤:

第1步:SystemConfiguration框架添加到项目中.


第2步:将以下代码导入您的header文件.

#import <SystemConfiguration/SystemConfiguration.h>
Run Code Online (Sandbox Code Playgroud)

第3步:使用以下方法

  • 类型1:

    - (BOOL) currentNetworkStatus {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        BOOL connected;
        BOOL isConnected;
        const char *host = "www.apple.com";
        SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host);
        SCNetworkReachabilityFlags flags;
        connected = SCNetworkReachabilityGetFlags(reachability, &flags);
        isConnected = NO;
        isConnected = connected && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired);
        CFRelease(reachability);
        return isConnected;
    }
    
    Run Code Online (Sandbox Code Playgroud)

  • 类型2:

    导入标题:#import "Reachability.h"

    - (BOOL)currentNetworkStatus
    {
        Reachability *reachability = [Reachability reachabilityForInternetConnection];
        NetworkStatus networkStatus = [reachability currentReachabilityStatus];
        return networkStatus != NotReachable;
    }
    
    Run Code Online (Sandbox Code Playgroud)

第4步:如何使用:

- (void)CheckInternet
{
    BOOL network = [self currentNetworkStatus];
    if (network)
    {
        NSLog(@"Network Available");
    }
    else
    {
        NSLog(@"No Network Available");
    }
}
Run Code Online (Sandbox Code Playgroud)


Mut*_*awe 12

-(void)newtworkType {

 NSArray *subviews = [[[[UIApplication sharedApplication] valueForKey:@"statusBar"] valueForKey:@"foregroundView"]subviews];
NSNumber *dataNetworkItemView = nil;

for (id subview in subviews) {
    if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
        dataNetworkItemView = subview;
        break;
    }
}


switch ([[dataNetworkItemView valueForKey:@"dataNetworkType"]integerValue]) {
    case 0:
        NSLog(@"No wifi or cellular");
        break;

    case 1:
        NSLog(@"2G");
        break;

    case 2:
        NSLog(@"3G");
        break;

    case 3:
        NSLog(@"4G");
        break;

    case 4:
        NSLog(@"LTE");
        break;

    case 5:
        NSLog(@"Wifi");
        break;


    default:
        break;
}
}
Run Code Online (Sandbox Code Playgroud)

  • 即使设备连接到Wifi或其他某种网络类型,互联网连接仍然无法使用.简单测试:连接到家庭wifi,然后拔掉电缆调制解调器.仍然连接到wifi,但零互联网. (7认同)

IOS*_*cks 11

- (void)viewWillAppear:(BOOL)animated
{
    NSString *URL = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];

    return (URL != NULL ) ? YES : NO;
}
Run Code Online (Sandbox Code Playgroud)

或者使用Reachability类.

使用iPhone SDK有两种方法可以检查Internet可用性:

1.检查Google页面是否已打开.

2.可达性等级

有关更多信息,请参阅Reachability(Apple Developer).


Huy*_*ran 10

使用http://huytd.github.io/datatify/.它比自己添加库和编写代码更容易.


Par*_*ara 10

第一:添加CFNetwork.framework框架

代码:ViewController.m

#import "Reachability.h"

- (void)viewWillAppear:(BOOL)animated
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"];
    NetworkStatus internetStatus = [r currentReachabilityStatus];

    if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
    {
        /// Create an alert if connection doesn't work
        UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:@"No Internet Connection"   message:NSLocalizedString(@"InternetMessage", nil)delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [myAlert show];
        [myAlert release];
    }
    else
    {
         NSLog(@"INTERNET IS CONNECT");
    }
}
Run Code Online (Sandbox Code Playgroud)


Ely*_*Ely 9

使用 iOS 12 或macOS v10.14 (Mojave) 或更新版本时,您可以使用NWPathMonitor代替 pre-historicReachability类。作为奖励,您可以轻松检测当前的网络连接类型:

import Network // Put this on top of your class

let monitor = NWPathMonitor()

monitor.pathUpdateHandler = { path in
    if path.status != .satisfied {
        // Not connected
    }
    else if path.usesInterfaceType(.cellular) {
        // Cellular 3/4/5g connection
    }
    else if path.usesInterfaceType(.wifi) {
        // Wi-Fi connection
    }
    else if path.usesInterfaceType(.wiredEthernet) {
        // Ethernet connection
    }
}

monitor.start(queue: DispatchQueue.global(qos: .background))
Run Code Online (Sandbox Code Playgroud)

更多信息:https : //developer.apple.com/documentation/network/nwpathmonitor


小智 8

首先下载可访问性类,并在您的Xcode中放入reachability.h和reachabilty.m文件.

最好的方法是创建一个通用的Function类(NSObject),以便您可以在任何类中使用它.这是网络连接可达性检查的两种方法:

+(BOOL) reachabiltyCheck
{
    NSLog(@"reachabiltyCheck");
    BOOL status =YES;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                          selector:@selector(reachabilityChanged:)
                                          name:kReachabilityChangedNotification
                                          object:nil];
    Reachability * reach = [Reachability reachabilityForInternetConnection];
    NSLog(@"status : %d",[reach currentReachabilityStatus]);
    if([reach currentReachabilityStatus]==0)
    {
        status = NO;
        NSLog(@"network not connected");
    }
    reach.reachableBlock = ^(Reachability * reachability)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
        });
    };
    reach.unreachableBlock = ^(Reachability * reachability)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
        });
    };
    [reach startNotifier];
    return status;
}

+(BOOL)reachabilityChanged:(NSNotification*)note
{
    BOOL status =YES;
    NSLog(@"reachabilityChanged");
    Reachability * reach = [note object];
    NetworkStatus netStatus = [reach currentReachabilityStatus];
    switch (netStatus)
    {
        case NotReachable:
            {
                status = NO;
                NSLog(@"Not Reachable");
            }
            break;

        default:
            {
                if (!isSyncingReportPulseFlag)
                {
                    status = YES;
                    isSyncingReportPulseFlag = TRUE;
                    [DatabaseHandler checkForFailedReportStatusAndReSync];
                }
            }
            break;
    }
    return status;
}

+ (BOOL) connectedToNetwork
{
    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    if (!didRetrieveFlags)
    {
        NSLog(@"Error. Could not recover network reachability flags");
        return NO;
    }
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;
    NSURL *testURL = [NSURL URLWithString:@"http://www.apple.com/"];
    NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL  cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];
    NSURLConnection *testConnection = [[NSURLConnection alloc] initWithRequest:testRequest delegate:self];
    return ((isReachable && !needsConnection) || nonWiFi) ? (testConnection ? YES : NO) : NO;
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以通过调用此类方法来检查任何类中的网络连接.


Sah*_*jan 8

还有另一种使用iPhone SDK检查Internet连接的方法.

尝试为网络连接实现以下代码.

#import <SystemConfiguration/SystemConfiguration.h>
#include <netdb.h>

/**
     Checking for network availability. It returns
     YES if the network is available.
*/
+ (BOOL) connectedToNetwork
{

    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability =
        SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;

    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);

    if (!didRetrieveFlags)
    {
        printf("Error. Could not recover network reachability flags\n");
        return NO;
    }

    BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
    BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);

    return (isReachable && !needsConnection) ? YES : NO;
}
Run Code Online (Sandbox Code Playgroud)


Piy*_*bey 8

我发现简单易用的库SimplePingHelper.

示例代码:chrishulbert/SimplePingHelper(GitHub)


小智 8

  1. 下载可访问性文件,https: //gist.github.com/darkseed/1182373

  2. CFNetwork.framework在框架中添加'SystemConfiguration.framework'

  3. #import"Reachability.h"


第一:添加CFNetwork.framework框架

代码:ViewController.m

- (void)viewWillAppear:(BOOL)animated
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"];
    NetworkStatus internetStatus = [r currentReachabilityStatus];

    if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
    {
        /// Create an alert if connection doesn't work
        UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:@"No Internet Connection"   message:NSLocalizedString(@"InternetMessage", nil)delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [myAlert show];
        [myAlert release];
    }
    else
    {
         NSLog(@"INTERNET IS CONNECT");
    }
}
Run Code Online (Sandbox Code Playgroud)


Dur*_*n.H 7

可达性类是确定以找出是否Internet连接可用的设备或不...

但是在访问Intranet资源的情况下:

使用可访问性类对Intranet服务器进行Ping操作始终返回true.

因此,在这种情况下,快速解决方案是创建一个pingme与该服务上的其他Web方法一起调用的Web方法.本pingme应该返回的东西.

所以我在常用函数上编写了以下方法

-(BOOL)PingServiceServer
{
    NSURL *url=[NSURL URLWithString:@"http://www.serveraddress/service.asmx/Ping"];

    NSMutableURLRequest *urlReq=[NSMutableURLRequest requestWithURL:url];

    [urlReq setTimeoutInterval:10];

    NSURLResponse *response;

    NSError *error = nil;

    NSData *receivedData = [NSURLConnection sendSynchronousRequest:urlReq
                                                 returningResponse:&response
                                                             error:&error];
    NSLog(@"receivedData:%@",receivedData);

    if (receivedData !=nil)
    {
        return YES;
    }
    else
    {
        NSLog(@"Data is null");
        return NO;
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的方法对我来说非常有用,所以每当我尝试将一些数据发送到服务器时,我总是使用这个低超时URLRequest来检查我的Intranet资源的可达性.


Ton*_*ony 7

要做到这一点非常简单.以下方法将起作用.请确保不允许使用名称传递主机名协议(如HTTP,HTTPS等).

-(BOOL)hasInternetConnection:(NSString*)urlAddress
{
    SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [urlAddress UTF8String]);
    SCNetworkReachabilityFlags flags;
    if (!SCNetworkReachabilityGetFlags(ref, &flags))
    {
        return NO;
    }
    return flags & kSCNetworkReachabilityFlagsReachable;
}
Run Code Online (Sandbox Code Playgroud)

它快速简单,无痛.


小智 7

除了可达性之外,您还可以使用Simple Ping帮助程序库.它工作得非常好,并且易于集成.


Min*_*wzy 7

我认为这是最好的答案.

"是"表示已连接."否"表示断开连接.

#import "Reachability.h"

 - (BOOL)canAccessInternet
{
    Reachability *IsReachable = [Reachability reachabilityForInternetConnection];
    NetworkStatus internetStats = [IsReachable currentReachabilityStatus];

    if (internetStats == NotReachable)
    {
        return NO;
    }
    else
    {
        return YES;
    }
}
Run Code Online (Sandbox Code Playgroud)


Dev*_*del 7

迅捷3 /迅捷4

您必须先导入

import SystemConfiguration
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方法检查互联网连接

func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
            SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
        }
    }

    var flags = SCNetworkReachabilityFlags()
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
        return false
    }
    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    return (isReachable && !needsConnection)

}
Run Code Online (Sandbox Code Playgroud)


Him*_*jan 6

导入Reachable.h您的类ViewController,并使用以下代码检查连接:

     #define hasInternetConnection [[Reachability reachabilityForInternetConnection] isReachable]
     if (hasInternetConnection){
           // To-do block
     }
Run Code Online (Sandbox Code Playgroud)


Ann*_*nny 6

  • 第1步:在项目中添加Reachability类.
  • 第2步:导入Reachability类
  • 第3步:创建以下功能

    - (BOOL)checkNetConnection {
        self.internetReachability = [Reachability reachabilityForInternetConnection];
        [self.internetReachability startNotifier];
        NetworkStatus netStatus = [self.internetReachability currentReachabilityStatus];
        switch (netStatus) {
            case NotReachable:
            {
                return NO;
            }
    
            case ReachableViaWWAN:
            {
                 return YES;
            }
    
            case ReachableViaWiFi:
            {
                 return YES;
            }
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 第4步:调用以下函数:

    if (![self checkNetConnection]) {
        [GlobalFunctions showAlert:@""
                         message:@"Please connect to the Internet!"
                         canBtntitle:nil
                         otherBtnTitle:@"Ok"];
        return;
    }
    else
    {
        Log.v("internet is connected","ok");
    }
    
    Run Code Online (Sandbox Code Playgroud)


ViJ*_*had 6

检查(iOS)Xcode 8,Swift 3.0中的Internet连接可用性

这是检查网络可用性的简单方法,例如我们的设备是否连接到任何网络.我已设法将其翻译为Swift 3.0,并在此处为最终代码.现有的Apple Reachability类和其他第三方库似乎太复杂,无法转换为Swift.

这适用于3G,4G和WiFi连接.

不要忘记将"SystemConfiguration.framework"添加到项目构建器中.

//Create new swift class file Reachability in your project.
import SystemConfiguration
public class InternetReachability {

class func isConnectedToNetwork() -> Bool {
   var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
   zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
   zeroAddress.sin_family = sa_family_t(AF_INET)
   let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
          SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
   }
   var flags: SCNetworkReachabilityFlags = 0
   if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
          return false
   }
   let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
   let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0

   return isReachable && !needsConnection
  }
}

// Check network connectivity from anywhere in project by using this code.
 if InternetReachability.isConnectedToNetwork() == true {
         print("Internet connection OK")
  } else {
         print("Internet connection FAILED")
  }
Run Code Online (Sandbox Code Playgroud)


小智 6

Swift 5 及更高版本:

public class Reachability {
    class func isConnectedToNetwork() -> Bool {
        var zeroAddress = sockaddr_in()
        zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
        zeroAddress.sin_family = sa_family_t(AF_INET)

        guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
                SCNetworkReachabilityCreateWithAddress(nil, $0)
            }
        }) else {
            return false
        }

        var flags: SCNetworkReachabilityFlags = []
        if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
            return false
        }

        let isReachable = flags.contains(.reachable)
        let needsConnection = flags.contains(.connectionRequired)

        return (isReachable && !needsConnection)
    }
Run Code Online (Sandbox Code Playgroud)

像这样调用这个类:

if Reachability.isConnectedToNetwork() == true {
    // Do something
} else {
    // Do something
}
Run Code Online (Sandbox Code Playgroud)


小智 5

对于我的 iOS 项目,我建议使用

可达性等级

在 Swift 中声明。对我来说,它与

Wi-Fi 和蜂窝数据

import SystemConfiguration

public class Reachability {

    class func isConnectedToNetwork() -> Bool {

        var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
        zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)

        let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
                SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
            }
        }

        var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
        if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
            return false
        }

        let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
        let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
        let ret = (isReachable && !needsConnection)
        return ret
    }
}
Run Code Online (Sandbox Code Playgroud)

使用条件语句,

if Reachability.isConnectedToNetwork() {
    // Enter your code here
}
}
else {
    print("NO Internet connection")
}
Run Code Online (Sandbox Code Playgroud)

此类几乎在您的应用程序使用 Internet 连接的所有情况下都很有用。如条件为真,则可调用API或执行任务。