mhxbpq
Last Updated: September 16, 2016
·
8.417K
· isuruj
Me

Checking For Internet Connection Availability

===================================================================

There are many libraries for checking the internet connection availability out there. But currently none of them are converted to Swift. This is the Swift implementation of the simple method to test the internet connection written by Chris Danielson in his blog post.

It's based on the SCNetworkReachability API. Don't forget to add the SystemConfiguration framework to your project.

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(sizeofValue(zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)

        let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
            SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
        }

        var flags: SCNetworkReachabilityFlags = 0
        if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
            return false
        }

        let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
        let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0

        return (isReachable && !needsConnection) ? true : false
    }

}

You can use it like this.

if Reachability.isConnectedToNetwork() {
    println("Haz Interwebz!")
} else {
    println("Oh noes! No interwebz!!!")
}

Get the source code from my Github.


Credits

Say Thanks
Respond

2 Responses
Add your response

17656
Ctrzuja3 normal

This is great! Thanks a lot :)

over 1 year ago ·
24809
None

If you're looking for a full implementation of Apple's Reachability lib in Swift, you could try https://github.com/ashleymills/Reachability.swift

Ash

over 1 year ago ·