我想使用 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 中已被弃用),如果是这样,有什么更好的方法来实现这一点?
I would like to check to see if I have an Internet connection on iOS using the Cocoa Touch libraries or on macOS using the Cocoa libraries.
I came up with a way to do this using an NSURL
. The way I did it seems a bit unreliable (because even Google could one day be down and relying on a third party seems bad), and while I could check to see for a response from some other websites if Google didn't respond, it does seem wasteful and an unnecessary overhead on my application.
- (BOOL)connectedToInternet {
NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
return ( URLString != NULL ) ? YES : NO;
}
Is what I have done bad, (not to mention stringWithContentsOfURL
is deprecated in iOS 3.0 and macOS 10.4) and if so, what is a better way to accomplish this?
发布评论
评论(30)
重要:此检查应始终异步执行。下面的大多数答案都是同步的,所以要小心,否则你的应用程序会冻结。
Swift
通过 CocoaPods 或 Carthage 安装:https://github.com/ashleymills/Reachability.swift
通过闭包测试可达性
Objective-C
将
SystemConfiguration
框架添加到项目中,但不用担心将其包含在任何地方添加 Tony Million 版本的
Reachability.h
和Reachability.m
到项目(在这里找到:https://github.com/tonymillion/Reachability)更新界面部分
然后在您可以调用的视图控制器的.m文件中实现此方法
重要提示:
Reachability
类是项目中最常用的类之一,因此您可以运行与其他项目的命名冲突。如果发生这种情况,您必须将一对Reachability.h
和Reachability.m
文件重命名为其他文件才能解决该问题。注意:您使用的域并不重要。它只是测试通往任何域的网关。
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
Install via CocoaPods or Carthage: https://github.com/ashleymills/Reachability.swift
Test reachability via closures
Objective-C
Add
SystemConfiguration
framework to the project but don't worry about including it anywhereAdd Tony Million's version of
Reachability.h
andReachability.m
to the project (found here: https://github.com/tonymillion/Reachability)Update the interface section
Then implement this method in the .m file of your view controller which you can call
Important Note: The
Reachability
class is one of the most used classes in projects so you might run into naming conflicts with other projects. If this happens, you'll have to rename one of the pairs ofReachability.h
andReachability.m
files to something else to resolve the issue.Note: The domain you use doesn't matter. It's just testing for a gateway to any domain.
我喜欢让事情变得简单。我这样做的方法是:
然后,每当我想查看是否有连接时,我都会使用此方法:
此方法不会等待网络状态更改才能执行操作。它只是在您要求时测试状态。
I like to keep things simple. The way I do this is:
Then, I use this whenever I want to see if I have a connection:
This method doesn't wait for changed network statuses in order to do stuff. It just tests the status when you ask it to.
使用 Apple 的 Reachability 代码,我创建了一个函数,可以正确检查这一点,而无需包含任何类。
在您的项目中包含 SystemConfiguration.framework。
进行一些导入:
现在只需调用此函数:
并且它已经为您进行了 iOS 5 测试。
Using Apple's Reachability code, I created a function that'll check this correctly without you having to include any classes.
Include the SystemConfiguration.framework in your project.
Make some imports:
Now just call this function:
And it's iOS 5 tested for you.
这曾经是正确的答案,但现在已经过时了,因为您应该订阅通知以实现可达性。此方法同步检查:
您可以使用 Apple 的 Reachability 类。它还允许您检查 Wi-Fi 是否已启用:
Reachability 类不随 SDK 一起提供,而是 此 Apple 示例应用程序。只需下载它,然后将 Reachability.h/m 复制到您的项目中即可。此外,您还必须将 SystemConfiguration 框架添加到您的项目中。
This used to be the correct answer, but it is now outdated as you should subscribe to notifications for reachability instead. This method checks synchronously:
You can use Apple's Reachability class. It will also allow you to check if Wi-Fi is enabled:
The Reachability class is not shipped with the SDK, but rather a part of this Apple sample application. Just download it, and copy Reachability.h/m to your project. Also, you have to add the SystemConfiguration framework to your project.
这是一个非常简单的答案:
URL 应该指向一个非常小的网站。我在这里使用 Google 的移动网站,但如果我有可靠的网络服务器,我会上传一个仅包含一个字符的小文件以获得最大速度。
如果您想要做的就是检查设备是否以某种方式连接到互联网,那么我绝对推荐使用这个简单的解决方案。如果您需要了解用户如何连接,那么使用 Reachability 是最佳选择。
小心:这会在加载网站时短暂阻止您的线程。就我而言,这不是问题,但您应该考虑这一点(感谢 Brad 指出了这一点)。
Here's a very simple answer:
The URL should point to an extremely small website. I use Google's mobile website here, but if I had a reliable web server I'd upload a small file with just one character in it for maximum speed.
If checking whether the device is somehow connected to the Internet is everything you want to do, I'd definitely recommend using this simple solution. If you need to know how the user is connected, using Reachability is the way to go.
Careful: This will briefly block your thread while it loads the website. In my case, this wasn't a problem, but you should consider this (credits to Brad for pointing this out).
以下是我在应用程序中执行此操作的方法:虽然 200 状态响应代码不能保证任何内容,但它对我来说足够稳定。这不需要像这里发布的 NSData 答案那么多的加载,因为我的只是检查 HEAD 响应。
Swift 代码
Objective-C 代码
Here is how I do it in my apps: While a 200 status response code doesn't guarantee anything, it is stable enough for me. This doesn't require as much loading as the NSData answers posted here, as mine just checks the HEAD response.
Swift Code
Objective-C Code
Apple 提供示例代码来检查不同类型的网络可用性。另外,iPhone 开发人员指南中还有一个示例。
注意:请参阅 @KHG 对此答案有关 Apple 可达性代码的使用的评论。
Apple supplies sample code to check for different types of network availability. Alternatively there is an example in the iPhone developers cookbook.
Note: Please see @KHG's comment on this answer regarding the use of Apple's reachability code.
您可以通过 使用
Reachability
(可用在这里)。You could use
Reachability
by (available here).Apple 提供了一个示例应用程序来执行此操作:
Reachability
Apple provides a sample app which does exactly this:
Reachability
使用 iOS 12 或 macOS v10.14 (Mojave) 或更高版本时,您可以使用
NWPathMonitor
而不是史前的Reachability
类。作为奖励,您可以轻松检测当前的网络连接类型:更多信息请参见:https://developer. apple.com/documentation/network/nwpathmonitor
When using iOS 12 or macOS v10.14 (Mojave) or newer, you can use
NWPathMonitor
instead of the pre-historicReachability
class. As a bonus you can easily detect the current network connection type:More info here: https://developer.apple.com/documentation/network/nwpathmonitor
仅更新了 Reachability 类。您现在可以使用:
Only the Reachability class has been updated. You can now use:
如果您使用
AFNetworking
您可以使用其自己的实现来获取互联网可达性状态。使用 AFNetworking 的最佳方法是子类化 AFHTTPClient 类并使用此类进行网络连接。
使用这种方法的优点之一是,当可达性状态发生变化时,您可以使用
块
来设置所需的行为。假设我创建了AFHTTPClient
的单例子类(如 AFNetworking 文档)名为BKHTTPClient
,我会执行以下操作:您还可以专门使用
AFNetworkReachabilityStatusReachableViaWWAN
和AFNetworkReachabilityStatusReachableViaWiFi
枚举(更多信息请参见此处)。If you're using
AFNetworking
you can use its own implementation for internet reachability status.The best way to use
AFNetworking
is to subclass theAFHTTPClient
class and use this class to do your network connections.One of the advantages of using this approach is that you can use
blocks
to set the desired behavior when the reachability status changes. Supposing that I've created a singleton subclass ofAFHTTPClient
(as said on the "Subclassing notes" on AFNetworking docs) namedBKHTTPClient
, I'd do something like:You could also check for Wi-Fi or WLAN connections specifically using the
AFNetworkReachabilityStatusReachableViaWWAN
andAFNetworkReachabilityStatusReachableViaWiFi
enums (more here).非常简单...尝试以下步骤:
第 1 步:将
SystemConfiguration
框架添加到您的项目中。第 2 步:将以下代码导入到您的
header
文件中。第 3 步:使用以下方法
类型 1:
类型 2:
导入标头:
#import "Reachability.h"
第 4 步:
Very simple.... Try these steps:
Step 1: Add the
SystemConfiguration
framework into your project.Step 2: Import the following code into your
header
file.Step 3: Use the following method
Type 1:
Type 2:
Import header :
#import "Reachability.h"
Step 4: How to use:
或者使用Reachability 类。
使用 iPhone SDK 检查互联网可用性的方法有两种:
1.检查Google页面是否打开。
2. Reachability 类
有关详细信息,请参阅可达性(Apple 开发人员)。
Or use the Reachability class.
There are two ways to check Internet availability using the iPhone SDK:
1. Check the Google page is opened or not.
2. Reachability Class
For more information, please refer to Reachability (Apple Developer).
首先:在框架中添加
CFNetwork.framework
代码:
ViewController.m
First: Add
CFNetwork.framework
in frameworkCode:
ViewController.m
Swift 3 / Swift 4
您必须先导入
您可以使用以下方法检查互联网连接:
Swift 3 / Swift 4
You must first import
You can check the Internet connection with the following method:
对于我的 iOS 项目,我建议使用
在 Swift 中声明。对我来说,它工作得很好
使用条件语句,
此类在您的应用使用 Internet 连接的几乎所有情况下都很有用。
例如,如果条件为真,则可以调用API或可以执行任务。
For my iOS projects, I recommend using
Declared in Swift. For me, it works simply fine with
Use a conditional statement,
This class is useful in almost every case your app uses the Internet connection.
Such as if the condition is true, API can be called or task could be performed.
下载可达性文件,https://gist.github.com/darkseed/1182373
并在框架中添加
CFNetwork.framework
和 'SystemConfiguration.framework'Do #import "Reachability.h"
首先:在框架中添加
CFNetwork.framework
代码:
ViewController.m
Download the Reachability file, https://gist.github.com/darkseed/1182373
And add
CFNetwork.framework
and 'SystemConfiguration.framework' in frameworkDo #import "Reachability.h"
First: Add
CFNetwork.framework
in frameworkCode:
ViewController.m
首先下载reachability类并将reachability.h和reachabilty.m文件放入您的Xcode中。
最好的方法是创建一个通用的 Functions 类(NSObject),以便您可以在任何类中使用它。这是用于网络连接可达性检查的两种方法:
现在,您可以通过调用此类方法来检查任何类中的网络连接。
First download the reachability class and put reachability.h and reachabilty.m file in your Xcode.
The best way is to make a common Functions class (NSObject) so that you can use it any class. These are two methods for a network connection reachability check:
Now you can check network connection in any class by calling this class method.
还有另一种方法使用 iPhone SDK 检查互联网连接。
尝试为网络连接实现以下代码。
There is also another method to check Internet connection using the iPhone SDK.
Try to implement the following code for the network connection.
自己做这件事非常简单。下面的方法会起作用。请确保不允许将主机名协议(例如 HTTP、HTTPS 等)与名称一起传入。
它快速简单且无痛。
To do this yourself is extremely simple. The following method will work. Just be sure to not allow a hostname protocol such as HTTP, HTTPS, etc. to be passed in with the name.
It is quick simple and painless.
我认为这是最好的答案。
“是”表示已连接。 “否”意味着断开连接。
I think this one is the best answer.
"Yes" means connected. "No" means disconnected.
Reachability 类可以确定设备的 Internet 连接是否可用...
但是在访问 Intranet 资源时:
使用以下命令对 Intranet 服务器执行 Ping 操作 :可达性类始终返回 true。
因此,这种情况下的快速解决方案是创建一个名为
pingme
的 Web 方法以及服务上的其他 Web 方法。pingme
应该返回一些东西。所以我在常用功能上写了以下方法
上面的方法对我来说非常有用,所以每当我尝试向服务器发送一些数据时,我总是使用这个低超时 URLRequest 检查我的内网资源的可达性。
The Reachability class is OK to find out if the Internet connection is available to a device or not...
But in case of accessing an intranet resource:
Pinging the intranet server with the reachability class always returns true.
So a quick solution in this scenario would be to create a web method called
pingme
along with other webmethods on the service.The
pingme
should return something.So I wrote the following method on common functions
The above method was so useful for me, so whenever I try to send some data to the server I always check the reachability of my intranet resource using this low timeout URLRequest.
Swift 5 及更高版本:
像这样调用此类:
Swift 5 and later:
Call this class like this:
步骤 3:创建以下函数
步骤 4:调用函数如下:
Step 3: Create the below function
Step 4: Call the function as below:
检查 (iOS) Xcode 8、Swift 3.0 中的互联网连接可用性
Checking the Internet connection availability in (iOS) Xcode 8 , Swift 3.0
在
ViewController
中导入Reachable.h
类,并使用以下代码检查连接性:Import
Reachable.h
class in yourViewController
, and use the following code to check connectivity:导入“可达性.h”
import "Reachability.h"
创建
AFNetworkReachabilityManager
对象并使用以下代码来跟踪网络连接Create an object of
AFNetworkReachabilityManager
and use the following code to track the network connectivity