猿问
下载APP

在Swift中检查互联网连接可用性

有没有一种方法可以使用Swift检查互联网连接是否可用?

我知道有很多第三方库可以执行此操作,但是它们都是用Objective-C编写的。我正在寻找Swift的替代方案。


守候你守候我
浏览 49回答 3
3回答

皈依舞

如评论中所述,尽管可以在Swift中使用Objective-C库,但我想要一个更纯净的Swift解决方案。现有的Apple Reachability类和其他第三方库对于我来说转换为Swift似乎太复杂了。我用Google搜索了更多内容,然后发现本文显示了一种检查网络可用性的简单方法。我着手将其翻译为Swift。我遇到了很多麻烦,但是由于来自StackOverflow的Martin R,我设法解决了这些麻烦,并最终在Swift中获得了可行的解决方案。这是代码。import Foundationimport SystemConfigurationpublic class Reachability {&nbsp; &nbsp; class func isConnectedToNetwork() -> Bool {&nbsp; &nbsp; &nbsp; &nbsp; 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))&nbsp; &nbsp; &nbsp; &nbsp; zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))&nbsp; &nbsp; &nbsp; &nbsp; zeroAddress.sin_family = sa_family_t(AF_INET)&nbsp; &nbsp; &nbsp; &nbsp; let defaultRouteReachability = withUnsafePointer(&zeroAddress) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; var flags: SCNetworkReachabilityFlags = 0&nbsp; &nbsp; &nbsp; &nbsp; if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0&nbsp; &nbsp; &nbsp; &nbsp; let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0&nbsp; &nbsp; &nbsp; &nbsp; return isReachable && !needsConnection&nbsp; &nbsp; }}对于Swift> 3.0public class Reachability {&nbsp; &nbsp; public func isConnectedToNetwork() -> Bool {&nbsp; &nbsp; &nbsp; &nbsp; var zeroAddress = sockaddr_in()&nbsp; &nbsp; &nbsp; &nbsp; zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)&nbsp; &nbsp; &nbsp; &nbsp; zeroAddress.sin_family = sa_family_t(AF_INET)&nbsp; &nbsp; &nbsp; &nbsp; guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SCNetworkReachabilityCreateWithAddress(nil, $0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }) else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; var flags: SCNetworkReachabilityFlags = []&nbsp; &nbsp; &nbsp; &nbsp; if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if flags.isEmpty {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; let isReachable = flags.contains(.reachable)&nbsp; &nbsp; &nbsp; &nbsp; let needsConnection = flags.contains(.connectionRequired)&nbsp; &nbsp; &nbsp; &nbsp; return (isReachable && !needsConnection)&nbsp; &nbsp; }}这适用于3G和WiFi连接。我还通过一个工作示例将其上传到了我的GitHub。

偶然的你

我给你更好的办法?你必须创建一个类与此代码&nbsp;import Foundation&nbsp;public class Reachability {class func isConnectedToNetwork()->Bool{&nbsp; &nbsp; var Status:Bool = false&nbsp; &nbsp; let url = NSURL(string: "http://google.com/")&nbsp; &nbsp; let request = NSMutableURLRequest(URL: url!)&nbsp; &nbsp; request.HTTPMethod = "HEAD"&nbsp; &nbsp; request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData&nbsp; &nbsp; request.timeoutInterval = 10.0&nbsp; &nbsp; var response: NSURLResponse?&nbsp; &nbsp; var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: nil) as NSData?&nbsp; &nbsp; if let httpResponse = response as? NSHTTPURLResponse {&nbsp; &nbsp; &nbsp; &nbsp; if httpResponse.statusCode == 200 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Status = true&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return Status&nbsp; }}然后你就可以在任何地方在项目中使用此代码检查Internet连接:if Reachability.isConnectedToNetwork() == true {&nbsp; &nbsp; &nbsp;println("Internet connection OK")} else {&nbsp; &nbsp; &nbsp;println("Internet connection FAILED")}很容易!*这种方式是基于维克拉姆POTE答案!

jeck猫

对于Swift 3.1(iOS 10.1)如果要区分网络类型(即WiFi或WWAN),请执行以下操作:您可以使用:func checkWiFi() -> Bool {&nbsp; &nbsp; let networkStatus = Reachability().connectionStatus()&nbsp; &nbsp; switch networkStatus {&nbsp; &nbsp; case .Unknown, .Offline:&nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; case .Online(.WWAN):&nbsp; &nbsp; &nbsp; &nbsp; print("Connected via WWAN")&nbsp; &nbsp; &nbsp; &nbsp; return true&nbsp; &nbsp; case .Online(.WiFi):&nbsp; &nbsp; &nbsp; &nbsp; print("Connected via WiFi")&nbsp; &nbsp; &nbsp; &nbsp; return true&nbsp; &nbsp; }}这是区分网络类型的整个Reachability-Class:import Foundationimport SystemConfigurationimport UIKitimport SystemConfiguration.CaptiveNetworkpublic let ReachabilityStatusChangedNotification = "ReachabilityStatusChangedNotification"public enum ReachabilityType: CustomStringConvertible {&nbsp; &nbsp; case WWAN&nbsp; &nbsp; case WiFi&nbsp; &nbsp; public var description: String {&nbsp; &nbsp; &nbsp; &nbsp; switch self {&nbsp; &nbsp; &nbsp; &nbsp; case .WWAN: return "WWAN"&nbsp; &nbsp; &nbsp; &nbsp; case .WiFi: return "WiFi"&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}public enum ReachabilityStatus: CustomStringConvertible&nbsp; {&nbsp; &nbsp; case Offline&nbsp; &nbsp; case Online(ReachabilityType)&nbsp; &nbsp; case Unknown&nbsp; &nbsp; public var description: String {&nbsp; &nbsp; &nbsp; &nbsp; switch self {&nbsp; &nbsp; &nbsp; &nbsp; case .Offline: return "Offline"&nbsp; &nbsp; &nbsp; &nbsp; case .Online(let type): return "Online (\(type))"&nbsp; &nbsp; &nbsp; &nbsp; case .Unknown: return "Unknown"&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}public class Reachability {&nbsp; &nbsp; func connectionStatus() -> ReachabilityStatus {&nbsp; &nbsp; &nbsp; &nbsp; var zeroAddress = sockaddr_in()&nbsp; &nbsp; &nbsp; &nbsp; zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))&nbsp; &nbsp; &nbsp; &nbsp; zeroAddress.sin_family = sa_family_t(AF_INET)&nbsp; &nbsp; &nbsp; &nbsp; guard let defaultRouteReachability = (withUnsafePointer(to: &zeroAddress) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { zeroSockAddress in&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }) else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return .Unknown&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; var flags : SCNetworkReachabilityFlags = []&nbsp; &nbsp; &nbsp; &nbsp; if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return .Unknown&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return ReachabilityStatus(reachabilityFlags: flags)&nbsp; &nbsp; }&nbsp; &nbsp; func monitorReachabilityChanges() {&nbsp; &nbsp; &nbsp; &nbsp; let host = "google.com"&nbsp; &nbsp; &nbsp; &nbsp; var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)&nbsp; &nbsp; &nbsp; &nbsp; let reachability = SCNetworkReachabilityCreateWithName(nil, host)!&nbsp; &nbsp; &nbsp; &nbsp; SCNetworkReachabilitySetCallback(reachability, { (_, flags, _) in&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let status = ReachabilityStatus(reachabilityFlags: flags)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; NotificationCenter.default.post(name: NSNotification.Name(rawValue: ReachabilityStatusChangedNotification), object: nil, userInfo: ["Status": status.description])}, &context)&nbsp; &nbsp; &nbsp; &nbsp; SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(), CFRunLoopMode.commonModes.rawValue)&nbsp; &nbsp; }}extension ReachabilityStatus {&nbsp; &nbsp; public init(reachabilityFlags flags: SCNetworkReachabilityFlags) {&nbsp; &nbsp; &nbsp; &nbsp; let connectionRequired = flags.contains(.connectionRequired)&nbsp; &nbsp; &nbsp; &nbsp; let isReachable = flags.contains(.reachable)&nbsp; &nbsp; &nbsp; &nbsp; let isWWAN = flags.contains(.isWWAN)&nbsp; &nbsp; &nbsp; &nbsp; if !connectionRequired && isReachable {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if isWWAN {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self = .Online(.WWAN)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self = .Online(.WiFi)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self =&nbsp; .Offline&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP
我要回答