这是 Apple 的 Reachability
类的即插即用替代品。它支持 ARC,并使用新的 GCD 方法来通知网络接口的变化。
除了标准的 NSNotification
,它还支持在网络变为可达和不可达时使用 blocks。
最后,您可以指定 WWAN 连接是否被认为是“可达”的。
一旦您将 .h/m
文件添加到项目中,请执行以下操作:
项目->目标->构建阶段->链接二进制与库
。SystemConfiguration.framework
。结束。
此示例使用 blocks 来通知接口状态已更改。Blocks 将在 后台线程 上调用,因此您需要将 UI 更新调度到主线程。
// Allocate a reachability object
Reachability* reach = [Reachability reachabilityWithHostname:@"www.google.com"];
// Set the blocks
reach.reachableBlock = ^(Reachability*reach)
{
NSLog(@"REACHABLE!");
};
reach.unreachableBlock = ^(Reachability*reach)
{
NSLog(@"UNREACHABLE!");
};
// Start the notifier, which will cause the reachability object to retain itself!
[reach startNotifier];
NSNotification
示例此示例将使用 NSNotification
来通知接口状态已更改。它们将在 主线程 上传递,因此您可以在函数内部进行 UI 更新。
此外,它将 Reachability
对象请求将 WWAN (3G/EDGE/CDMA) 视为一个不可达的连接(例如,如果您正在编写视频流应用程序,您可能需要这样操作以节省用户的流量套餐)。
// Allocate a reachability object
Reachability* reach = [Reachability reachabilityWithHostname:@"www.google.com"];
// Tell the reachability that we DON'T want to be reachable on 3G/EDGE/CDMA
reach.reachableOnWWAN = NO;
// Here we set up a NSNotification observer. The Reachability that caused the notification
// is passed in the object parameter
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
[reach startNotifier]
访问 使用 Reachability 的项目 并为“MAX WINS!”添加您自己的项目。