Skip to content

Instantly share code, notes, and snippets.

@enigmatic7earth
Created October 12, 2018 13:14
Show Gist options
  • Save enigmatic7earth/21530996909cc17f2f1e441ade0e569e to your computer and use it in GitHub Desktop.
Save enigmatic7earth/21530996909cc17f2f1e441ade0e569e to your computer and use it in GitHub Desktop.
Reachability in Swift 4
//
// Reachability.swift
//
//
// Created by NETBIZ on 12/10/18.
// Copyright © 2018 Netbiz.in. All rights reserved.
//
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(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 = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
// Working for Cellular and WIFI
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
let ret = (isReachable && !needsConnection)
return ret
}
}
//
// ViewController.swift
//
//
// Created by NETBIZ on 17/09/18.
// Copyright © 2018 Netbiz.in. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Check for connectivity
if Reachability.isConnectedToNetwork() == true {
// code to execute if internet is available
} else {
let alert = UIAlertController(title: "Connection Issue", message: "Please check your internet connection, you seem to be offline. Offline weather data of a previous location will be shown until you are online again. ", preferredStyle: .alert)
let ok = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(ok)
present(alert, animated: true, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment