检查互联网连接(iOS 10)

对于iOS 9,我使用Reachability public class来检查设备是否连接到互联网。 我将我的Swift 2代码转换成Swift 3,并且Reachability不再工作。 有人能告诉我如何检查iOS 10上的互联网连接吗? 谢谢! 以下是代码片段:

open class Reachability { class func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) } var flags = SCNetworkReachabilityFlags() if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) { return false } let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return (isReachable && !needsConnection) } } 
 import Foundation import SystemConfiguration func isInternetAvailable() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress) } } var flags = SCNetworkReachabilityFlags() if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) { return false } let isReachable = flags.contains(.reachable) let needsConnection = flags.contains(.connectionRequired) return (isReachable && !needsConnection) } 

这适用于iOS 10

SWIFT 3.0 :这是非常简单的方法:

 import SystemConfiguration protocol Utilities { } extension NSObject:Utilities{ enum ReachabilityStatus { case notReachable case reachableViaWWAN case reachableViaWiFi } var currentReachabilityStatus: ReachabilityStatus { 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 .notReachable } var flags: SCNetworkReachabilityFlags = [] if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) { return .notReachable } if flags.contains(.reachable) == false { // The target host is not reachable. return .notReachable } else if flags.contains(.isWWAN) == true { // WWAN connections are OK if the calling application is using the CFNetwork APIs. return .reachableViaWWAN } else if flags.contains(.connectionRequired) == false { // If the target host is reachable and no connection is required then we'll assume that you're on Wi-Fi... return .reachableViaWiFi } else if (flags.contains(.connectionOnDemand) == true || flags.contains(.connectionOnTraffic) == true) && flags.contains(.interventionRequired) == false { // The connection is on-demand (or on-traffic) if the calling application is using the CFSocketStream or higher APIs and no [user] intervention is needed return .reachableViaWiFi } else { return .notReachable } } } 

然后你可以在你的项目的任何地方使用它,例如:

  func viewDidLoad(){ print(currentReachabilityStatus != .notReachable) //true connected } 

试试这个,首先 SystemConfiguration 导入到你的类中。

 import SystemConfiguration 

现在执行波纹pipefunction。

 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(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress) } } var flags = SCNetworkReachabilityFlags() if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) { return false } let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return (isReachable && !needsConnection) } 

第1步:在您的项目中创build一个swift文件。 我创build了“ConnectionCheck.swift”

第2步:在你的“ConnectionCheck.swift”文件和“导入SystemConfiguration”文件中添加这个代码到你的“ConnectionCheck.swift”和“ViewController.swift”

 import Foundation import SystemConfiguration public class ConnectionCheck { class 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 } let isReachable = flags.contains(.reachable) let needsConnection = flags.contains(.connectionRequired) return (isReachable && !needsConnection) } 

}

第3步:现在在“ViewController.swift”使用此代码来检查networking可达性

 if ConnectionCheck.isConnectedToNetwork() { print("Connected") } else{ print("disConnected") } 

这里是通过callback函数的Swift 3解决scheme, isConnectedToNetwork()是由Yasin Ugurlu从上面的解决scheme中提取出来的。

 class func isInternetAvailable(webSiteToPing: String?, completionHandler: @escaping (Bool) -> Void) { // 1. Check the WiFi Connection guard isConnectedToNetwork() else { completionHandler(false) return } // 2. Check the Internet Connection var webAddress = "https://www.google.com" // Default Web Site if let _ = webSiteToPing { webAddress = webSiteToPing! } guard let url = URL(string: webAddress) else { completionHandler(false) print("could not create url from: \(webAddress)") return } let urlRequest = URLRequest(url: url) let session = URLSession.shared let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in if error != nil || response == nil { completionHandler(false) } else { completionHandler(true) } }) task.resume() } 

这个代码对你有帮助。 它在Swift 4和Xcode 9中为我工作

转到https://github.com/ashleymills/Reachability.swift/tree/master/Reachability并将Reachability.swift文件复制到您的项目;

Vasil Nunev明确解释了这种可达性https://www.youtube.com/watch?v=wDZmz9IsB-8

 class ViewController: UIViewController { let reachability = Reachability(); override func viewDidLoad() { super.viewDidLoad() reachability?.whenReachable = { _ in DispatchQueue.main.async { self.view.backgroundColor = UIColor.green } } reachability?.whenUnreachable = { _ in DispatchQueue.main.async { self.view.backgroundColor = UIColor.red } } NotificationCenter.default.addObserver(self, selector: #selector(internetChanged), name: Notification.Name.reachabilityChanged , object: reachability) do{ try reachability?.startNotifier() }catch{ print("Could not start notifier:\(error)") } } @objc func internetChanged(note:Notification) { let reachability = note.object as! Reachability if reachability.connection != .none { if reachability.connection == .wifi{ DispatchQueue.main.async { self.view.backgroundColor = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1) } }else if reachability.connection == .cellular{ DispatchQueue.main.async { self.view.backgroundColor = #colorLiteral(red: 0.3647058904, green: 0.06666667014, blue: 0.9686274529, alpha: 1) } } }else{ DispatchQueue.main.async { self.view.backgroundColor = #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1) } } } } 

你可以在swift中使用3

 import SystemConfiguration class Connection { 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(kCFAllocatorDefault, UnsafePointer($0)) } var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0) if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false { return false } let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return isReachable && !needsConnection } }