繁体   English   中英

如何在 iOS 或 macOS 上检查活动的互联网连接?

[英]How can I check for an active Internet connection on iOS or macOS?

我想检查一下我是否在使用Cocoa Touch库的 iOS 或使用Cocoa库的 macOS 上有互联网连接。

我想出了一种使用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 中已弃用),如果是这样,有什么更好的方法来实现这一点?

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


迅速

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

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

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

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

我喜欢保持简单。 我这样做的方法是:

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

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

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

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


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

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

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

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 是您想做的一切,我绝对建议您使用这个简单的解决方案。 如果您需要知道用户是如何连接的,那么使用 Reachability 是一种可行的方法。

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

以下是我在我的应用程序中的做法:虽然 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
         }
    }];
}

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

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

您可以通过  使用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.

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

可达性

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

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

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

可达性

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

使用AFNetworking的最佳方法是AFHTTPClient类并使用此类进行网络连接。

使用这种方法的优点之一是,当可达性状态发生变化时,您可以使用blocks来设置所需的行为。 假设我已经创建的单子AFHTTPClient (作为对“子类钞”说AFNetworking文档)命名BKHTTPClient ,我会做一些事情,如:

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

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

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

我还没有对每一种可以想象的连接(如临时 Wi-Fi)进行详尽的测试。

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

步骤 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; }

第四步:如何使用:

- (void)CheckInternet
{
    BOOL network = [self currentNetworkStatus];
    if (network)
    {
        NSLog(@"Network Available");
    }
    else
    {
        NSLog(@"No Network Available");
    }
}
-(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;
}
}
- (void)viewWillAppear:(BOOL)animated
{
    NSString *URL = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];

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

或者使用Reachability 类

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

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

2.可达性类

更多信息请参考可达性(苹果开发者)。

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

第一:在框架中添加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");
    }
}

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

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

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

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

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

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

我发现库SimplePingHelper简单易用。

示例代码: chrishurbert/SimplePingHelperGitHub

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

斯威夫特 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)
}

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 检查我的内网资源的可达性。

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

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

它快速简单且无痛。

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

我认为这是最好的答案。

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

#import "Reachability.h"

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

    if (internetStats == NotReachable)
    {
        return NO;
    }
    else
    {
        return YES;
    }
}

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

     #define hasInternetConnection [[Reachability reachabilityForInternetConnection] isReachable]
     if (hasInternetConnection){
           // To-do block
     }
  • 步骤 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; } } }
  • 第四步:调用函数如下:

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

我想检查一下我是否在使用Cocoa Touch库的iOS上或在使用Cocoa库的macOS上建立了Internet连接。

我想出了一种使用NSURL做到这一点的方法。 我这样做的方式似乎有点不可靠(因为即使Google可能有一天会倒闭,依赖第三方也似乎很糟糕),而且我可以检查是否其他一些网站做出了回应(如果Google没有回应的话),的确看起来很浪费,而且对我的应用程序来说不必要的开销。

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

我做的不stringWithContentsOfURL (更不用说在iOS 3.0和macOS 10.4中不推荐使用stringWithContentsOfURL ),如果是的话,有什么更好的方法来实现?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM