我想检查我是否在使用Cocoa Touch库的iOS上或在使用Cocoa库的macOS上建立了Internet连接。
我想出了一种使用NSURL
执行此操作的方法。我这样做的方式似乎有点不可靠(因为即使Google可能有一天会倒闭,依赖第三方也似乎很糟糕),而且我可以检查一下是否有其他网站的响应(如果Google没有响应),确实看起来很浪费,而且对我的应用程序来说也没有不必要的开销。
- (BOOL) connectedToInternet
{
NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
return ( URLString != NULL ) ? YES : NO;
}
我做的不好吗(更不用说
stringWithContentsOfURL
在iOS 3.0和macOS 10.4中已弃用),如果是的话,有什么更好的方法来做到这一点? 最佳答案
重要提示:此检查应始终异步执行。以下大多数答案是同步的,因此请小心,否则将冻结您的应用程序。
迅速
1)通过CocoaPods或迦太基安装:https://github.com/ashleymills/Reachability.swift
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")
}
目标C
1)将
SystemConfiguration
框架添加到项目中,但不必担心将其包含在任何地方2)将Tony Million的
Reachability.h
和Reachability.m
版本添加到项目中(在此处找到:https://github.com/tonymillion/Reachability)3)更新界面部分
#import "Reachability.h"
// Add this to the interface in the .m file of your view controller
@interface MyViewController ()
{
Reachability *internetReachableFoo;
}
@end
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];
}
重要说明:
Reachability
类是项目中最常用的类之一,因此您可能会遇到与其他项目的命名冲突。如果发生这种情况,则必须将成对的Reachability.h
和Reachability.m
文件之一重命名为其他名称才能解决此问题。注意:您使用的域无关紧要。它只是测试通往任何域的网关。
关于ios - 如何在iOS或macOS上检查事件的Internet连接?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6792181/