我想检查一下我是否在使用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
),如果是的话,有什么更好的方法来做到这一点?
#1楼
这里有一个美观的,使用ARC和GCD的可达性现代化方案:
#2楼
您可以使用ach( 在此处提供 )使用可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.
#3楼
这是一个非常简单的答案:
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");
该网址应指向一个非常小的网站。 我在这里使用Google的移动网站,但是如果我有一个可靠的网络服务器,我将上传一个只有一个字符的小文件,以实现最大速度。
如果要检查设备是否以某种方式连接到Internet,我绝对会建议您使用此简单的解决方案。 如果您需要了解用户的连接方式,则可以使用“可达性”。
注意:加载网站时,这会暂时阻止您的线程。 就我而言,这不是问题,但您应该考虑一下(Brad指出了这一点)。
#4楼
苹果提供了一个示例应用程序,它可以完成以下操作:
#5楼
Apple提供了示例代码来检查不同类型的网络可用性。 另外,iPhone开发人员手册中也有一个示例 。
注意:有关使用Apple可达性代码的信息,请参阅@KHG关于此答案的评论。
#6楼
我在此讨论中使用了代码,而且看起来工作正常(阅读整个线程!)。
我还没有对每种可能的连接方式(例如临时Wi-Fi)进行详尽的测试。
#7楼
这曾经是正确的答案,但现在已经过时,因为您应该订阅通知以获取可达性。 此方法同步检查:
您可以使用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类,而是该Apple示例应用程序的一部分。 只需下载它,然后将Reachability.h / m复制到您的项目中即可。 同样,您必须将SystemConfiguration框架添加到您的项目中。
#8楼
- (void)viewWillAppear:(BOOL)animated
{
NSString *URL = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
return (URL != NULL ) ? YES : NO;
}
或使用Reachability类 。
有两种方法可以使用iPhone SDK检查Internet可用性:
1.检查Google页面是否打开。
2.可达性等级
有关更多信息,请参阅可达性 (Apple Developer)。
#9楼
这是我在应用程序中的操作方法:虽然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
}
}];
}
#10楼
如果您使用的是AFNetworking
,则可以使用其自己的实现来实现Internet可达性状态。
使用AFNetworking
的最佳方法是对AFHTTPClient
类进行子类化,并使用该类进行网络连接。
使用此方法的优点之一是,当可达性状态发生更改时,可以使用blocks
来设置所需的行为。 假设我已经创建的单子AFHTTPClient
(作为对“子类钞”说AFNetworking文档 )命名BKHTTPClient
,我会做一些事情,如:
BKHTTPClient *httpClient = [BKHTTPClient sharedClient];
[httpClient setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
{
if (status == AFNetworkReachabilityStatusNotReachable)
{
// Not reachable
}
else
{
// Reachable
}
}];
您还可以专门使用AFNetworkReachabilityStatusReachableViaWWAN
和AFNetworkReachabilityStatusReachableViaWiFi
枚举来检查Wi-Fi或WLAN连接( 此处更多信息 )。
#11楼
-(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楼
首先下载可到达性类,然后在Xcode中放入reachability.h和reachabilty.m文件。
最好的方法是制作一个通用的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;
}
现在,您可以通过调用此类方法检查任何类中的网络连接。
#13楼
可达性类可以确定设备是否可以使用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资源的可访问性。
#14楼
使用http://huytd.github.io/datatify/ 。 这比添加库和自己编写代码要容易得多。
#15楼
在您的ViewController
导入Reachable.h
类,并使用以下代码检查连接性 :
#define hasInternetConnection [[Reachability reachabilityForInternetConnection] isReachable]
if (hasInternetConnection){
// To-do block
}
#16楼
还有另一种使用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;
}
#17楼
自己做到这一点非常简单。 以下方法将起作用。 只是要确保不允许使用名称传递HTTP,HTTPS等主机名协议。
-(BOOL)hasInternetConnection:(NSString*)urlAddress
{
SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [urlAddress UTF8String]);
SCNetworkReachabilityFlags flags;
if (!SCNetworkReachabilityGetFlags(ref, &flags))
{
return NO;
}
return flags & kSCNetworkReachabilityFlagsReachable;
}
快速,简单,无痛。
#18楼
我发现使用SimplePingHelper库非常简单。
示例代码: chrishulbert / SimplePingHelper ( GitHub )
#19楼
除了可访问性之外,您还可以使用Simple Ping帮助程序库 。 它的工作原理非常好,易于集成。
#20楼
第一 :在框架中添加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");
}
}
#21楼
非常简单...。请尝试以下步骤:
步骤1:将SystemConfiguration
框架添加到您的项目中。
步骤2:将以下代码导入到您的header
文件中。
#import <SystemConfiguration/SystemConfiguration.h>
步骤3:使用以下方法
类型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");
}
}
#22楼
我认为这是最好的答案。
“是”表示已连接。 “否”表示断开连接。
#import "Reachability.h"
- (BOOL)canAccessInternet
{
Reachability *IsReachable = [Reachability reachabilityForInternetConnection];
NetworkStatus internetStats = [IsReachable currentReachabilityStatus];
if (internetStats == NotReachable)
{
return NO;
}
else
{
return YES;
}
}
#23楼
并在框架中添加
CFNetwork.framework
和'SystemConfiguration.framework'执行#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");
}
}
#24楼
- 步骤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; } } }
步骤4:调用以下函数:
if (![self checkNetConnection]) { [GlobalFunctions showAlert:@"" message:@"Please connect to the Internet!" canBtntitle:nil otherBtnTitle:@"Ok"]; return; } else { Log.v("internet is connected","ok"); }
#25楼
在(iOS)Xcode 8和Swift 3.0中检查Internet连接可用性
这是一种检查网络可用性的简单方法,就像我们的设备是否连接到任何网络一样。 我已经设法将其翻译为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")
}
#26楼
仅可达性类已更新。 您现在可以使用:
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");}
#27楼
重要提示 :此检查应始终异步执行。 以下大多数答案是同步的,因此请小心,否则将冻结您的应用程序。
迅速
1)通过CocoaPods或迦太基安装: 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")
}
物镜
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
文件对中的一个重命名为其他名称才能解决此问题。
注意:您使用的域无关紧要。 它只是测试通往任何域的网关。
#28楼
迅捷3 /迅捷4
您必须先导入
import SystemConfiguration
您可以通过以下方法检查互联网连接
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)
}
#29楼
我喜欢保持简单。 我这样做的方式是:
//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
}
此方法无需等待更改网络状态即可完成工作。 当您要求时,它只是测试状态。
#30楼
使用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 。
#31楼
iOS 5的可达性版本是darkseed / Reachability.h 。 不是我的! =)