Check if internet connection availabile in swift [duplicate]
Asked Answered
C

3

13

Is there an Apple framework bundle to detect if there's an internet connection? Currently my application crashes when it tries to geolocate the user's position without an internet connection.

/*inside locationManager didUpdateLocations method*/
var currentLocation:CLLocation? = locations[0] as? CLLocation
geocoder = CLGeocoder()
//Crashes on line below when there isn't an internet connection
//Need to add function to check if internet connection is live 
//Before running reverseGeocodeLocation
geocoder.reverseGeocodeLocation (currentLocation,handleGeocode)

I'm a bit new to swift and ios programming - my apologies.

Crinkle answered 20/6, 2014 at 19:53 Comment(7)
Since Swift can send messages to Objective-C objects, the answer to that other question applies here. If you have trouble integrating that answer into your project, feel free to create a new question asking for help with that.Pipage
Rob, I'm looking for a swift solution not an objective-c solution... In my opinion I want all my code to be in swift and not in objective-c, so that its easier to maintain in 1 language. I have the belief that long term all code will have to be "ported" over to swift. I guess I'll have to rewrite the Reachability class in swift to do that?Crinkle
Maybe you could rewrite it in Swift. Since it's built on a C framework (SystemConfiguration) that requires registering callback functions, it will require more than a beginner's knowledge of Swift.Pipage
It's a great idea to have all your code in Swift, but Apple went through a lot of trouble to bridge the two languages for us. Swift was created specifically to live alongside Objective-C -- don't run away from that.Pyroelectricity
Nate - They bridged it to help with migrating users over to swift. I believe long term objective c will fade away.Crinkle
@Crinkle the cocoa touch api is written in ObjC it's not going anywhere for a long time. I love Swift, you'll be better at it if you learn ObjCSade
What's the actual error you're getting when it crashes?Sneeze
V
22

Not a full-fledged network checking library but I found this simple method for checking the network availability. I managed to translate it to Swift and here the final code.

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
    }

}

It works for both 3G and WiFi connections. I've also uploaded it to my Github with a working example. If you're looking for a simple way to check for network availability purely in Swift, you can use it.

Vlf answered 10/9, 2014 at 20:25 Comment(2)
FYI this is also works on OS X.Steelmaker
What if my 3G is switched ON, but i don't have data package? Will it return me true?Syncarpous
M
4

Using Babatunde's code sample but here is an updated version for Swift 2.0 and error handling: EDIT: Also changed the URL for Google as HTTPS for iOS 9. EDIT2: Original article: http://www.brianjcoleman.com/tutorial-check-for-internet-connection-in-swift/

import Foundation
import SystemConfiguration

public class Reachability {

    // Check if internet connection is available

    class func isConnectedToNetwork() -> Bool {

        var status:Bool = false

        let url = NSURL(string: "https://google.com")
        let request = NSMutableURLRequest(URL: url!)
        request.HTTPMethod = "HEAD"
        request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
        request.timeoutInterval = 10.0

        var response:NSURLResponse?

        do {
            let _ = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response) as NSData?
        }
        catch let error as NSError {
            print(error.localizedDescription)
        }

        if let httpResponse = response as? NSHTTPURLResponse {
            if httpResponse.statusCode == 200 {
                status = true
            }
        }
        return status
   }
}
Morville answered 4/9, 2015 at 17:1 Comment(0)
L
1

As Reachability has not been fully ported to swift yet, you can use the sample code below to check for internet connection:

public class Reachability {
/**
 * Check if internet connection is available
 */
class func isConnectedToNetwork() -> Bool {
    var status:Bool = false

    let url = NSURL(string: "http://google.com")
    let request = NSMutableURLRequest(URL: url!)
    request.HTTPMethod = "HEAD"
    request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
    request.timeoutInterval = 10.0

    var response:NSURLResponse?

    var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: nil) as NSData?

    if let httpResponse = response as? NSHTTPURLResponse {
        if httpResponse.statusCode == 200 {
            status = true
        }
    }

    return status
  }
}

See sample usage of the function below:

// Check if internet is available before proceeding further
    if Reachability.isConnectedToNetwork() {
        // Go ahead and fetch your data from the internet
        // ...
    } else {
        println("Internet connection not available")

        var alert = UIAlertView(title: "No Internet connection", message: "Please ensure you are connected to the Internet", delegate: nil, cancelButtonTitle: "OK")
        alert.show()
    }
Lowkey answered 17/4, 2015 at 8:3 Comment(1)
To work above solution You must need to add : "NSAllowsArbitraryLoads key to YES under NSAppTransportSecurity dictionary in your info.plist file." Otherwise the code won't workSankey

© 2022 - 2024 — McMap. All rights reserved.