Important : This check should always be performed asynchronously.
(重要提示 :此检查应始终异步执行。)
The majority of answers below are synchronous so be careful otherwise you'll freeze up your app. (以下大多数答案是同步的,因此请小心,否则将冻结您的应用程序。)
Swift (迅速)
1) Install via CocoaPods or Carthage: https://github.com/ashleymills/Reachability.swift
(1)通过CocoaPods或迦太基安装: https : //github.com/ashleymills/Reachability.swift)
2) Test reachability via closures
(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) Add SystemConfiguration
framework to the project but don't worry about including it anywhere
(1)将SystemConfiguration
框架添加到项目中,但不必担心将其包含在任何地方)
2) Add Tony Million's version of Reachability.h
and Reachability.m
to the project (found here: https://github.com/tonymillion/Reachability )
(2)将Tony Million的Reachability.h
和Reachability.m
版本添加到项目中(可在此处找到: https : //github.com/tonymillion/Reachability ))
3) Update the interface section
(3)更新界面部分)
#import "Reachability.h"
// Add this to the interface in the .m file of your view controller
@interface MyViewController ()
{
Reachability *internetReachableFoo;
}
@end
4) Then implement this method in the .m file of your view controller which you can call
(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];
}
Important Note: The Reachability
class is one of the most used classes in projects so you might run into naming conflicts with other projects.
(重要说明: Reachability
类是项目中最常用的类之一,因此您可能会遇到与其他项目的命名冲突。)
If this happens, you'll have to rename one of the pairs of Reachability.h
and Reachability.m
files to something else to resolve the issue. (如果发生这种情况,则必须将Reachability.h
和Reachability.m
文件对中的一个重命名为其他名称才能解决此问题。)
Note: The domain you use doesn't matter.
(注意:您使用的域无关紧要。)
It's just testing for a gateway to any domain. (它只是测试通往任何域的网关。)