我想使用 Cocoa Touch 检查我在 iOS 上是否有互联网连接库或在 macOS 上使用 Cocoa图书馆。
我想到了一种使用 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 中被弃用了)如果是这样,什么是更好的方法来完成这个?
最佳答案
重要:此检查应始终异步执行。下面的大部分答案都是同步的,所以要小心,否则你的应用会死机。
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
然后在您可以调用的 View Controller 的.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
文件重命名为其他名称以解决问题。
注意:您使用的域无关紧要。它只是测试通往任何域的网关。
关于ios - 如何检查 iOS 或 macOS 上的互联网连接是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1083701/