协慌网

登录 贡献 社区

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

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

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

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

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

答案

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


迅速

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文件重命名为其他内容以解决此问题。

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

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

//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为您测试的。