Updated answer for Swift 4.0 & AlamoFire:
The answer I posted on Sept 18 is incorrect, it only detects if it is connected to network, not internet. Here is the correct solution using AlamoFire:
1) Create custom Reachability Observer class:
import Alamofire
class ReachabilityObserver {
fileprivate let reachabilityManager = NetworkReachabilityManager()
fileprivate var reachabilityStatus: NetworkReachabilityManager.NetworkReachabilityStatus = .unknown
var isOnline: Bool {
if (reachabilityStatus == .unknown || reachabilityStatus == .notReachable){
return false
}else{
return true
}
}
static let sharedInstance = ReachabilityObserver()
fileprivate init () {
reachabilityManager?.listener = {
[weak self] status in
self?.reachabilityStatus = status
NotificationCenter.default.post(
name: NSNotification.Name(rawValue: ClickUpConstants.ReachabilityStateChanged),
object: nil)
}
reachabilityManager?.startListening()
}
}
2) Initialize on app start up
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
_ = ReachabilityObserver.sharedInstance
return true
}
3) Use this anywhere in your app to detect if online, such as in view did load, or when action occurs
if (ReachabilityObserver.sharedInstance.isOnline){
//User is online
}else{
//User is not online
}