SQLTerminal.app
now available

XPath.app
now available
Want fresh tech tips in your inbox?

How to Check if Your iOS or MacOS App is Connected to the Internet

       

Is your app connected to the internet? You can use this standalone class to check! There are no dependencies so you can copy/paste it into your project without needing to install another framework.

With this class it's as simple as running Reachability.isConnectedToNetwork()

import Cocoa
import SystemConfiguration
// Usage
// if Reachability.isConnectedToNetwork() {
//   print("We're online!")
// }
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)
        guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
                SCNetworkReachabilityCreateWithAddress(nil, $0)
            }
        }) else {
            return false
        }
        var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
        if SCNetworkReachabilityGetFlags(defaultRouteReachability as! SCNetworkReachability, &flags) == false {
            return false
        }
        let isReachable = flags == .reachable
        let needsConnection = flags == .connectionRequired
        return isReachable && !needsConnection
    }
}

And here is a link to a gist Reachability.swift

Tagged w/ #ios #swift #macos #cocoa #networking #reachability #isconnectedtonetwork #online #xcode #apple

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
VocabReminder
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
VocabQuiz
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app