1377

我想查看是否在 iOS 上使用Cocoa Touch库或在 macOS 上使用Cocoa库连接到 Internet。

我想出了一种使用NSURL. 我这样做的方式似乎有点不可靠(因为即使谷歌有一天可能会失败并且依赖第三方似乎很糟糕),虽然如果谷歌没有回应,我可以查看其他网站的回应,它对我的应用程序来说似乎是浪费和不必要的开销。

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

我做错了什么(更不用说stringWithContentsOfURL在 iOS 3.0 和 macOS 10.4 中已弃用),如果是这样,有什么更好的方法来做到这一点?

4

46 回答 46

1307

重要提示:此检查应始终异步执行。下面的大多数答案都是同步的,所以要小心,否则你会冻结你的应用程序。


迅速

  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")
    }
    

Objective-C

  1. SystemConfiguration框架添加到项目中,但不必担心将其包含在任何地方

  2. 将 Tony Million 的Reachability.h和版本添加Reachability.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
    
  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];
    }
    

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

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

于 2010-08-29T23:58:19.800 回答
314

我喜欢让事情变得简单。我这样做的方法是:

//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;
}

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

if (![self connected]) {
    // Not connected
} else {
    // Connected. Do some Internet stuff
}

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

于 2011-08-26T13:34:17.580 回答
146

使用 Apple 的 Reachability 代码,我创建了一个函数,可以正确检查这一点,而无需包含任何类。

在您的项目中包含 SystemConfiguration.framework。

做一些进口:

#import <sys/socket.h>
#import <netinet/in.h>
#import <SystemConfiguration/SystemConfiguration.h>

现在只需调用此函数:

/*
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;
}

它是为您测试的iOS 5

于 2011-10-28T20:37:08.443 回答
123

这曾经是正确的答案,但现在已经过时了,因为您应该订阅通知以获得可访问性。此方法同步检查:


您可以使用 Apple 的可达性类。它还允许您检查是否启用了 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) { }

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

于 2009-07-05T10:58:02.347 回答
82

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

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");

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

如果检查设备是否以某种方式连接到 Internet 是您想要做的一切,我绝对推荐使用这个简单的解决方案。如果您需要了解用户是如何连接的,那么使用可达性是您的最佳选择。

小心:这将在加载网站时短暂阻止您的线程。就我而言,这不是问题,但您应该考虑这一点(感谢 Brad 指出这一点)。

于 2012-05-14T22:25:53.657 回答
73

以下是我在我的应用程序中执行此操作的方法:虽然 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
        }
    })
}

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
         }
    }];
}
于 2012-11-30T03:26:10.257 回答
57

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

注意:请参阅@KHG 对此答案关于使用 Apple 可达性代码的评论。

于 2009-07-05T08:59:47.217 回答
46

您可以使用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.
于 2012-04-25T12:20:38.653 回答
40

Apple 提供了一个示例应用程序,它正是这样做的:

可达性

于 2009-07-05T08:58:25.503 回答
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");}
于 2010-08-27T09:41:02.263 回答
27

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

于 2011-11-07T20:17:53.293 回答
25

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

可达性

于 2012-04-10T07:12:01.983 回答
22

如果您正在使用AFNetworking,您可以使用它自己的实现来获取 Internet 可访问性状态。

最好的使用方法AFNetworking是子类化AFHTTPClient该类并使用该类来进行网络连接。

使用这种方法的优点之一是您可以blocks在可达性状态发生变化时使用它来设置所需的行为。假设我创建了一个名为 的单例子类(如AFNetworking docsAFHTTPClient上的“子类化说明”中所述),我会执行以下操作:BKHTTPClient

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

AFNetworkReachabilityStatusReachableViaWWAN您还可以专门使用andAFNetworkReachabilityStatusReachableViaWiFi枚举来检查 Wi-Fi 或 WLAN 连接(更多信息在此处)。

于 2013-05-30T01:18:13.327 回答
18

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

我还没有对每一种可能的连接方式(比如 ad hoc Wi-Fi)进行详尽的测试。

于 2009-07-05T09:10:54.370 回答
17

在使用 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))

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

于 2020-10-20T11:37:45.900 回答
15

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

第 1 步:SystemConfiguration框架添加到您的项目中。


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

#import <SystemConfiguration/SystemConfiguration.h>

第三步:使用下面的方法

  • 类型 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;
    }
    

  • 类型 2:

    导入标头#import "Reachability.h"

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

第4步:如何使用:

- (void)CheckInternet
{
    BOOL network = [self currentNetworkStatus];
    if (network)
    {
        NSLog(@"Network Available");
    }
    else
    {
        NSLog(@"No Network Available");
    }
}
于 2014-04-15T12:42:05.990 回答
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;
}
}
于 2013-06-03T11:43:13.620 回答
11
- (void)viewWillAppear:(BOOL)animated
{
    NSString *URL = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];

    return (URL != NULL ) ? YES : NO;
}

或者使用可达性类

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

1.检查谷歌页面是否打开。

2.可达性类

有关更多信息,请参阅可达性(Apple 开发人员)。

于 2012-11-22T11:46:16.173 回答
10

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

于 2013-08-31T17:13:09.100 回答
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");
    }
}
于 2014-04-05T11:16:36.613 回答
9

斯威夫特 3 / 斯威夫特 4

您必须先导入

import SystemConfiguration

您可以通过以下方法检查 Internet 连接:

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)
}
于 2017-08-10T14:00:17.360 回答
8

首先下载可达性类并将reachability.h 和reachabilty.m 文件放在你的Xcode中。

最好的方法是制作一个通用的 Functions 类(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;
}

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

于 2013-06-07T13:53:13.097 回答
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;
}
于 2013-11-09T09:58:55.250 回答
8

我发现它简单易用的库SimplePingHelper

示例代码:chrishulbert/SimplePingHelper ( GitHub )

于 2014-01-07T09:04:48.053 回答
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");
    }
}
于 2014-11-27T07:29:36.037 回答
7

Reachability 类可以确定设备是否可以使用 Internet 连接...

但是在访问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;
    }
}

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

于 2013-07-10T12:42:53.217 回答
7

自己做这件事非常简单。以下方法将起作用。请确保不允许将主机名协议(例如 HTTP、HTTPS 等)与名称一起传入。

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

它快速简单且无痛。

于 2013-12-04T18:17:46.020 回答
7

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

于 2014-02-21T11:44:30.177 回答
7

我认为这是最好的答案。

“是”表示已连接。“否”表示断开连接。

#import "Reachability.h"

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

    if (internetStats == NotReachable)
    {
        return NO;
    }
    else
    {
        return YES;
    }
}
于 2014-10-01T10:49:02.887 回答
7

对于我的 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
    }
}

使用条件语句,

if Reachability.isConnectedToNetwork() {
    // Enter your code here
}
}
else {
    print("NO Internet connection")
}

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

于 2019-03-21T18:52:24.307 回答
6

在您的导入Reachable.hViewController,并使用以下代码检查连接性

#define hasInternetConnection [[Reachability reachabilityForInternetConnection] isReachable]
if (hasInternetConnection){
      // To-do block
}
于 2013-10-18T06:19:31.650 回答
6
  • 第 1 步:在您的项目中添加可达性类。
  • 第 2 步:导入可达性类
  • 第 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;
            }
        }
    }
    
  • 第四步:调用函数如下:

    if (![self checkNetConnection]) {
        [GlobalFunctions showAlert:@""
                         message:@"Please connect to the Internet!"
                         canBtntitle:nil
                         otherBtnTitle:@"Ok"];
        return;
    }
    else
    {
        Log.v("internet is connected","ok");
    }
    
于 2015-08-19T06:37:08.733 回答
6
于 2015-12-17T12:14:31.013 回答
3

从https://github.com/tonymillion/Reachability获取 Reachabilty 类,在您的项目中添加系统配置框架,在您的类中导入 Reachability.h 并实现如下自定义方法:

- (BOOL)isConnectedToInternet
{
    //return NO; // Force for offline testing
    Reachability *hostReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [hostReach currentReachabilityStatus];
    return !(netStatus == NotReachable);
}
于 2013-09-17T10:28:45.007 回答
3

导入“可达性.h”

-(BOOL)netStat
{
    Reachability *test = [Reachability reachabilityForInternetConnection];
    return [test isReachable];
}
于 2014-09-30T10:43:33.543 回答
3

创建一个对象AFNetworkReachabilityManager并使用以下代码跟踪网络连接

self.reachabilityManager = [AFNetworkReachabilityManager managerForDomain:@"yourDomain"];
[self.reachabilityManager startMonitoring];
[self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            case AFNetworkReachabilityStatusReachableViaWiFi:
                break;
            case AFNetworkReachabilityStatusNotReachable:
                break;
            default:
                break;
        }
    }];
于 2015-03-31T18:27:54.847 回答
3

使用 Xcode 9 和 Swift 4.0 检查 (iOS) 中的 Internet 连接可用性

请按照以下步骤操作

第1步:

创建一个扩展文件并将其命名为ReachabilityManager.swift。然后添加下面的代码行。

import Foundation
import SystemConfiguration
public class ConnectionCheck
{
    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)
    }
}

第 2 步:使用下面的代码调用上面的扩展程序。

if ConnectionCheck.isConnectedToNetwork()
{
     print("Connected")
     // Online related Business logic
}
else{
     print("disConnected")
     // Offline related business logic
}
于 2018-09-14T07:29:11.183 回答
2

这适用于 Swift 3.0 和异步。大多数答案是同步解决方案,如果您的连接速度非常慢,它将阻塞您的主线程。

这个解决方案更好,但并不完美,因为它依赖 Google 来检查连接,所以请随意使用其他 URL。

func checkInternetConnection(completionHandler:@escaping (Bool) -> Void)
{
    if let url = URL(string: "http://www.google.com/")
    {
        var request = URLRequest(url: url)
        request.httpMethod = "HEAD"
        request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
        request.timeoutInterval = 5

        let tast = URLSession.shared.dataTask(with: request, completionHandler:
        {
            (data, response, error) in

            completionHandler(error == nil)
        })
        tast.resume()
    }
    else
    {
        completionHandler(true)
    }
}
于 2016-10-17T15:29:23.933 回答
2
Pod `Alamofire` has `NetworkReachabilityManager`, you just have to create one function 

func isConnectedToInternet() ->Bool {
        return NetworkReachabilityManager()!.isReachable
}
于 2018-10-10T05:46:14.793 回答
2

请参阅介绍 Network.framework:Sockets 的现代替代方案

我们应该在某个时候摆脱可达性。

于 2018-12-13T06:06:53.940 回答
2

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)
    }

像这样调用这个类:

if Reachability.isConnectedToNetwork() == true {
    // Do something
} else {
    // Do something
}
于 2021-02-15T11:49:15.487 回答
1

阿拉莫菲尔

我知道问题是要求 Coca Touch 解决方案,但我想为在 iOS 上搜索检查 Internet 连接的人们提供一个解决方案,并且这里会有更多选择。

如果您已经在使用Alamofire,那么您可以从中受益。

您可以将以下类添加到您的应用程序中,并调用MNNetworkUtils.main.isConnected()以获取有关其是否已连接的布尔值。

#import Alamofire

class MNNetworkUtils {
  static let main = MNNetworkUtils()
  init() {
    manager = NetworkReachabilityManager(host: "google.com")
    listenForReachability()
  }

  private let manager: NetworkReachabilityManager?
  private var reachable: Bool = false
  private func listenForReachability() {
    self.manager?.listener = { [unowned self] status in
      switch status {
      case .notReachable:
        self.reachable = false
      case .reachable(_), .unknown:
        self.reachable = true
      }
    }
    self.manager?.startListening()
  }

  func isConnected() -> Bool {
    return reachable
  }
}

这是一个单例类。每次,当用户连接或断开网络时,它都会self.reachable正确地覆盖为真/假,因为我们开始监听NetworkReachabilityManager单例初始化。

此外,为了监控可达性,您需要提供主机。目前,我正在使用 google.com,但如果需要,可以随意更改为任何其他主机或您的主机。将类名和文件名更改为与您的项目匹配的任何内容。

于 2018-04-02T16:45:28.693 回答
1

请试试这个。它会帮助你(Swift 4)

  1. 通过 CocoaPods 或 Carthage安装可达性:可达性

  2. 导入Reachability并在Network类中使用

    import Reachability
    
    class Network {
    
       private let internetReachability : Reachability?
       var isReachable : Bool = false
    
       init() {
    
           self.internetReachability = Reachability.init()
           do{
               try self.internetReachability?.startNotifier()
               NotificationCenter.default.addObserver(self, selector: #selector(self.handleNetworkChange), name: .reachabilityChanged, object: internetReachability)
           }
           catch {
            print("could not start reachability notifier")
           }
       }
    
       @objc private func handleNetworkChange(notify: Notification) {
    
           let reachability = notify.object as! Reachability
           if reachability.connection != .none {
               self.isReachable = true
           }
           else {
               self.isReachable = false
           }
           print("Internet Connected : \(self.isReachable)") //Print Status of Network Connection
       }
    }
    
  3. 在需要的地方使用如下所示。

    var networkOBJ = Network()
    // Use "networkOBJ.isReachable" for Network Status
    print(networkOBJ.isReachable)
    
于 2019-08-09T11:43:47.707 回答
1
//
//  Connectivity.swift
// 
//
//  Created by Kausik Jati on 17/07/20.
// 
//

import Foundation
import Network

enum ConnectionState: String {
    case notConnected = "Internet connection not avalable"
    case connected = "Internet connection avalable"
    case slowConnection = "Internet connection poor"
}
protocol ConnectivityDelegate: class {
    func checkInternetConnection(_ state: ConnectionState, isLowDataMode: Bool)
}
class Connectivity: NSObject {
    private let monitor = NWPathMonitor()
    weak var delegate: ConnectivityDelegate? = nil
    private let queue = DispatchQueue.global(qos: .background)
    private var isLowDataMode = false
    static let instance = Connectivity()
private override init() {
    super.init()
    monitor.start(queue: queue)
    startMonitorNetwork()
}
private func startMonitorNetwork() {
    monitor.pathUpdateHandler = { path in
        if #available(iOS 13.0, *) {
            self.isLowDataMode = path.isConstrained
        } else {
            // Fallback on earlier versions
            self.isLowDataMode = false
        }
        
        if path.status == .requiresConnection {
            print("requiresConnection")
                self.delegate?.checkInternetConnection(.slowConnection, isLowDataMode: self.isLowDataMode)
        } else if path.status == .satisfied {
            print("satisfied")
                 self.delegate?.checkInternetConnection(.connected, isLowDataMode: self.isLowDataMode)
        } else if path.status == .unsatisfied {
            print("unsatisfied")
                self.delegate?.checkInternetConnection(.notConnected, isLowDataMode: self.isLowDataMode)
            }
        }
    
    }
    func stopMonitorNetwork() {
        monitor.cancel()
    }
}
于 2020-07-17T15:50:45.393 回答
0

Swift 5,Alamofire,主机

// Session reference
var alamofireSessionManager: Session!

func checkHostReachable(completionHandler: @escaping (_ isReachable:Bool) -> Void) {
    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = 1
    configuration.timeoutIntervalForResource = 1
    configuration.requestCachePolicy = .reloadIgnoringLocalCacheData

    alamofireSessionManager = Session(configuration: configuration)

    alamofireSessionManager.request("https://google.com").response { response in
        completionHandler(response.response?.statusCode == 200)
    }
}

// Using
checkHostReachable() { (isReachable) in
    print("isReachable:\(isReachable)")
}
于 2020-10-14T11:36:44.247 回答
-2

试试这个:

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error


if ([self.delegate respondsToSelector:@selector(getErrorResponse:)]) {
    [self.delegate performSelector:@selector(getErrorResponse:) withObject:@"No Network Connection"];
}

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"BMC" message:@"No Network Connection" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
[alertView show];

}

于 2016-11-18T07:51:06.327 回答