首页 文章

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

提问于
浏览
1264

我想查看我是否在iOS上使用Cocoa Touch库或使用Cocoa库在macOS上 Build 了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中被弃用)如果是这样,有什么更好的方法来实现这一目标?

30 回答

  • 8
    -(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;
    }
    }
    
  • 12

    First :在框架中添加 CFNetwork.framework

    CodeViewController.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");
        }
    }
    
  • 144

    还有另一种使用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;
    }
    
  • 71

    Reachability类可以确定设备是否可以使用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;
        }
    }
    

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

  • 39

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


    斯威夫特

    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.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
    

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

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

    Note: 您使用的域名不仅仅是测试任何域的网关 .

  • 25

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

  • 55

    使用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 .

  • 1241

    Checking the Internet connection availability in (iOS) Xcode 8 , Swift 3.0

    这是检查网络可用性的简单方法,例如我们的设备是否连接到任何网络 . 我已设法将其翻译为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")
      }
    
  • 6

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

  • 8

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

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


    Step 2: 将以下代码导入 header 文件 .

    #import <SystemConfiguration/SystemConfiguration.h>
    

    Step 3: 使用以下方法

    • Type 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;
    }
    

    • Type 2:

    Import header#import "Reachability.h"

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

    Step 4: 如何使用:

    - (void)CheckInternet
    {
        BOOL network = [self currentNetworkStatus];
        if (network)
        {
            NSLog(@"Network Available");
        }
        else
        {
            NSLog(@"No Network Available");
        }
    }
    
  • 304

    首先下载可达性类,并在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;
    }
    

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

  • 118

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

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

    它快速简单,无痛 .

  • 79

    您可以使用 Reachability by(available here) .

    #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.
    
  • 32

    ViewController 中导入 Reachable.h 类,并使用以下代码检查 connectivity

    #define hasInternetConnection [[Reachability reachabilityForInternetConnection] isReachable]
         if (hasInternetConnection){
               // To-do block
         }
    
  • 27

    First :在框架中添加 CFNetwork.framework

    CodeViewController.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");
        }
    }
    
  • 18

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

    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应指向一个非常小的网站 . 我使用Google 's mobile website here, but if I had a reliable web server I' d上传 a small file with just one character in it 以获得最高速度 .

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

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

  • 14

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

    Reachability

  • 11
    - (void)viewWillAppear:(BOOL)animated
    {
        NSString *URL = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
    
        return (URL != NULL ) ? YES : NO;
    }
    

    或者使用 Reachability class .

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

    1. Check the Google page is opened or not.

    2. Reachability Class

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

  • 10

    我认为这是最好的答案 .

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

    #import "Reachability.h"
    
     - (BOOL)canAccessInternet
    {
        Reachability *IsReachable = [Reachability reachabilityForInternetConnection];
        NetworkStatus internetStats = [IsReachable currentReachabilityStatus];
    
        if (internetStats == NotReachable)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    
  • 10

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

  • 8

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


    您可以使用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) { }
    

    SDK中不包含Reachability类,而是this Apple sample application的一部分 . 只需下载它,并将Reachability.h / m复制到您的项目中 . 此外,您必须将SystemConfiguration框架添加到项目中 .

  • 8

    我已经使用了this discussion中的代码,它似乎工作正常(阅读整个线程!) .

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

  • 8

    我发现它简单易用的库SimplePingHelper .

    示例代码:chrishulbert/SimplePingHelperGitHub

  • 7

    Apple提供sample code以检查不同类型的网络可用性 . 另外,iPhone开发者手册中有一个example .

    Note: 请参阅@KHG 's comment on this answer regarding the use of Apple' s可达性代码 .

  • 7
    • 步骤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;
            }
        }
    }
    
    • 步骤4:调用如下函数:
    if (![self checkNetConnection]) {
        [GlobalFunctions showAlert:@""
                         message:@"Please connect to the Internet!"
                         canBtntitle:nil
                         otherBtnTitle:@"Ok"];
        return;
    }
    else
    {
        Log.v("internet is connected","ok");
    }
    
  • 7

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

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

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

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

    您还可以使用 AFNetworkReachabilityStatusReachableViaWWANAFNetworkReachabilityStatusReachableViaWiFi 枚举(more here)专门检查Wi-Fi或WLAN连接 .

  • 6

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

    Reachability

  • 6

    只有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");}
    
  • 45

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

    Swift Code

    func checkInternet(flag:Bool, completionHandler:(internet:Bool) -> Void)
    {
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
    
        let url = NSURL(string: "http://www.appleiphonecell.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 Apple's region universal URL reachable
            }
            else
            {
                // No "Internet" aka Apple's region universal URL un-reachable
            }
        })
    }
    

    Objective-C Code

    typedef void(^connection)(BOOL);
    
    - (void)checkInternet:(connection)block
    {
        NSURL *url = [NSURL URLWithString:@"http://www.appleiphonecell.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 Apple's region universal URL reachable
             }
             else
             {
                 // No "Internet" aka Apple's region universal URL un-reachable
             }
        }];
    }
    
  • 22

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

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

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

相关问题