Important:此判断应异步执行always.下面的大多数答案都是同步的,所以要小心,否则会冻结您的应用程序.
Swift
通过CocoaPods或Carthage安装:https://github.com/ashleymills/Reachability.swift
通过闭包测试可达性
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
将SystemConfiguration
个框架添加到项目中,但不要担心在任何地方都要包含它
将Tony Million版本的Reachability.h
和Reachability.m
添加到该项目中(可在此处找到:https://github.com/tonymillion/Reachability)
更新接口节
#import "Reachability.h"
// Add this to the interface in the .m file of your view controller
@interface MyViewController ()
{
Reachability *internetReachableFoo;
}
@end
然后在视图控制器的.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];
}
Important Note: Reachability
类是项目中最常用的类之一,因此您可能会遇到与其他项目的命名冲突.如果发生这种情况,您将不得不将Reachability.h
和Reachability.m
文件对中的一个文件重命名为其他名称以解决该问题.
Note:你使用的域名并不重要.它只是在测试通向任何域的网关.