如何检查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;
}
是我做得不好,(更不用说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")
}
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.h
和Reachability.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已经过测试。
链接地址: http://www.djcxy.com/p/26375.html上一篇: How to check for an active Internet connection on iOS or macOS?