在 Swift 中检查互联网连接的可用性 [英] Check for internet connection availability in Swift
问题描述
有没有办法使用 Swift 检查互联网连接是否可用?
Is there a way to check if the internet connection is available using Swift?
我知道有很多第三方库可以做到这一点,但它们都是用 Objective-C 编写的.我正在寻找 Swift 替代品.
I know there are many third party libraries to do this but they are all written in Objective-C. I'm looking for a Swift alternative.
推荐答案
正如评论中提到的,虽然可以在 Swift 中使用 Objective-C 库,但我想要一个更纯粹的 Swift 解决方案.现有的 Apple Reachability 类和其他第三方库似乎太复杂了,我无法转换为 Swift.我在谷歌上搜索了更多,发现了这篇文章 显示了一种检查网络可用性的简单方法.我开始将其翻译成 Swift.我遇到了很多障碍,但感谢Martin R 来自 StackOverflow,我设法解决了它们并最终在 Swift 中获得了一个可行的解决方案.这是代码.
As mentioned in the comments, although its possible to use Objective-C libraries in Swift, I wanted a more pure Swift solution. The existing Apple Reachability class and other third party libraries seemed to be too complicated for me to translate to Swift. I Googled some more and I came across this article which shows a simple method to check for network availability. I set out to translate this to Swift. I hit many snags but thanks to Martin R from StackOverflow, I managed to resolve them and finally get a workable solution in Swift. Here is the code.
import Foundation
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
}
var flags: SCNetworkReachabilityFlags = 0
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
return false
}
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return isReachable && !needsConnection
}
}
对于 Swift > 3.0
public class Reachability {
public func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return false
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return false
}
if flags.isEmpty {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}
}
这适用于 3G 和 WiFi 连接.我还通过一个工作示例将其上传到了我的 GitHub.
This works for both 3G and WiFi connections. I've also uploaded it to my GitHub with a working example.
这篇关于在 Swift 中检查互联网连接的可用性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!