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.

PHPDave
  • 904
  • 1
  • 7
  • 15
  • 2
    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. – rob mayoff Jun 20 '14 at 19:58
  • 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? – PHPDave Jun 20 '14 at 20:03
  • 4
    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. – rob mayoff Jun 20 '14 at 20:13
  • 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. – Nate Cook Jun 21 '14 at 03:19
  • Nate - They bridged it to help with migrating users over to swift. I believe long term objective c will fade away. – PHPDave Jun 26 '14 at 16:46
  • 1
    @PHPDave 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 ObjC – Woodstock Aug 17 '14 at 08:48
  • What's the actual error you're getting when it crashes? – James Frost Sep 10 '14 at 20:41

3 Answers3

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.

Isuru
  • 30,617
  • 60
  • 187
  • 303
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
   }
}
Md. Najmul Hasan
  • 605
  • 1
  • 6
  • 19
Adrien
  • 275
  • 2
  • 8
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()
    }
Babatunde Adeyemi
  • 14,360
  • 4
  • 34
  • 26
  • 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 work – Sheetal Shinde Feb 06 '21 at 04:59