我想使用以下命令检查我在 iOS 上是否有互联网连接可可触感 https://en.wikipedia.org/wiki/Cocoa_Touch库或在 macOS 上使用Cocoa https://en.wikipedia.org/wiki/Cocoa_(API)图书馆。
我想出了一种方法来做到这一点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 中已弃用),如果是这样,有什么更好的方法来实现这一点?
重要的: 这个检查应该always异步执行。下面的大多数答案都是同步的,所以要小心,否则你的应用程序会冻结。
Swift
-
通过 CocoaPods 或 Carthage 安装:https://github.com/ashleymills/Reachability.swift 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
-
Add SystemConfiguration
项目的框架,但不用担心将其包含在任何地方
-
添加托尼·百万的版本Reachability.h
and Reachability.m
到项目(在这里找到:https://github.com/tonymillion/Reachability 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];
}
重要的提示: The Reachability
class 是项目中最常用的类之一,因此您可能会遇到与其他项目的命名冲突。如果发生这种情况,您将必须重命名其中一对Reachability.h
and Reachability.m
文件到其他东西来解决问题。
Note:您使用的域名并不重要。它只是测试通往任何域的网关。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)