swift3 - internet - reachability swift 4
Compruebe la conexión a Internet(iOS 10) (8)
Para iOS 9 estaba usando la clase pública Reachability para verificar si el dispositivo está conectado a Internet o no. Convertí mi código de Swift 2 a Swift 3, y el Alcance ya no funciona. ¿Puede alguien decirme cómo verificar la conexión a Internet en iOS 10? ¡Gracias! Aquí está el fragmento de código:
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)
}
}
Aquí está la solución Swift 3 a través de la función de devolución de llamada, isConnectedToNetwork()
es tomada de la solución por Yasin Ugurlu desde arriba.
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()
}
Este código sería útil para ti. funcionó para mí en Swift 4 y Xcode 9
Vaya a https://github.com/ashleymills/Reachability.swift/tree/master/Reachability y copie el archivo Reachability.swift a su proyecto
Vasil Nunev explica claramente esta Accesibilidad 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)
}
}
}
}
Intenta esto, funciona primero para mí, importa la configuración del sistema a tu clase.
import SystemConfiguration
Y ahora implementa la función de abajo.
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)
}
Puedes usar en 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
}
}
paso 1: crea un archivo rápido en tu proyecto. Creé "ConnectionCheck.swift"
paso 2: agregue este código en su archivo "ConnectionCheck.swift" e "import SystemConfiguration" a su "ConnectionCheck.swift" y "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)
}
}
paso 3: ahora en "ViewController.swift" use este código para verificar el alcance de la red
if ConnectionCheck.isConnectedToNetwork() {
print("Connected")
}
else{
print("disConnected")
}
SWIFT 3.0 : esta es una forma muy simple de hacerlo:
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
}
}
}
y luego simplemente puede usarlo en cualquier parte de su proyecto, por ejemplo:
func viewDidLoad(){
print(currentReachabilityStatus != .notReachable) //true connected
}
Swift 4 / Xcode 11:
Combinaría dos funciones (con pequeños cambios) de @Pavle Mijatovic y @Krutagn Patel (con agradecimiento) para responder la pregunta de @Lance Samaria. :)
Casi comprobé todas las posibilidades. (el código se puede mejorar, pero funciona bien)
tener una clase de la siguiente manera:
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)
}
class func isInternetAvailable(webSiteToPing: String?, completionHandler: @escaping (_ b: 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()
}
}
utilice el siguiente código donde necesita verificar la conexión a Internet: por ejemplo, en la función appDelegate -> applicationDidBecomeActive .
explicación: siempre que se llame a la función completionHandler (arriba), el resultado (verdadero o falso) se pasa al código siguiente como b
. Entonces, si b es cierto, tienes conexión a Internet.
let web : String? = "https://www.google.com"
ConnectionCheck.isInternetAvailable(webSiteToPing: web) { (b) in
print(b)
if b {
print("connected") // or do something here
} else {
print("disconnected") // or do something here
}
}
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)
}
Esto funciona en iOS 10