Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if internet connection availabile in swift [duplicate]

Tags:

ios

swift

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.

like image 460
PHPDave Avatar asked Jun 20 '14 19:06

PHPDave


People also ask

How do I know if my internet connection is swift?

Using Reachability. swift. In the viewWillAppear method, add an observer to the Notification Center, so every time the network state changes, like from Wifi goes to Cellular, this will be detected instantly and call the reachabilityChanged method.

How do I check my internet connection status?

Select the Start button, then type settings. Select Settings > Network & internet. The status of your network connection will appear at the top.

How do I check my Alamofire internet connection?

You can use NetworkReachabilityManager class from Alamofire and configure the isConnectedToInternet() method as per your need. I am only checking if the device is connected to internet or not. print("Yes! internet is available.") print("Yes! internet is available.")

How do I check my node internet connection?

A quick and dirty way is to check if Node can resolve www.google.com : require('dns'). resolve('www.google.com', function(err) { if (err) { console. log("No connection"); } else { console.


2 Answers

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.

like image 100
Isuru Avatar answered Nov 09 '22 12:11

Isuru


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
   }
}
like image 36
Adrien Avatar answered Nov 09 '22 11:11

Adrien