Create Reachability Using Swift 3 XCode 8

Source Code

import Foundation
import SystemConfiguration

//Create Queue for Reachability Callback
fileprivate let reachabilitySerialQueue = DispatchQueue(label: “com.kapilahuja.reachability.reachability”)

//Variable to save Reachability status and show toast if not reachable
var isInternetReachable = false {
didSet {
if !isInternetReachable {
ApplicationManager.sharedInstance.ShowInternetAlertToast()
}
}
}

/* Check Connectivity */
func isInternetAvailable()
{
// Create Network Configuration & Flag
// —– Start —–
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) {
isInternetReachable = false
return
}
// —– End —–

// Set Network Reachability Callback on status change of route & set queue for it
// —– Start —–
var context = SCNetworkReachabilityContext()
if !SCNetworkReachabilitySetCallback(defaultRouteReachability!, callback, &context) {
print(SCError())
}

if !SCNetworkReachabilitySetDispatchQueue(defaultRouteReachability!, reachabilitySerialQueue) {
print(SCError())
}
// —– End —–

// Get Network Status & Save it
// —– Start —–
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0

isInternetReachable = (isReachable && !needsConnection)
// —– End —–
}

func callback(reachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) {

//guard info != nil else { return }

// Get Network Status & Save it
// —– Start —–
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0

isInternetReachable = (isReachable && !needsConnection)
// —– End —–
}

Images

Screen Shot 2017-05-31 at 3.00.03 PM

Screen Shot 2017-05-31 at 3.00.14 PM

How to use

Initialize

//Check Connectivity
isInternetAvailable()

Use

if isInternetReachable {

}

Advertisements
Create Reachability Using Swift 3 XCode 8