2

I wanted this class to push or show an alertView saying it's not connected to Internet

public class Reachability {

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?


    do{
        var data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
        print(response)
    } catch {
        //handle error
        print(error)

    }


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

    return Status
}
}

Here is my declaration inside the mainViewcontroller(initial)

if Reachability.isConnectedToNetwork() == true {
 }else {
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            let viewController:UIViewController = (self.storyboard?.instantiateViewControllerWithIdentifier("SignInSignUpVCIdentifier"))!
            self.presentViewController(viewController, animated: true, completion: nil)
        })
    }//end of 

It doesn't push anything. It's showing making attempt 2 sleeping for 4.34324

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
suisied
  • 426
  • 1
  • 6
  • 19

3 Answers3

2

Try this to check the network connectivity of the device

import SystemConfiguration



func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)
    let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
        SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
    }

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

    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    return (isReachable && !needsConnection)
   }

Add the following code in your function to check the network is reachable or not and get the alert

   if self.isConnectedToNetwork() {
       print(self.isConnectedToNetwork())
       // isConnectedToNetwork == true
       // It comes here when its connected to network
       let alertController = UIAlertController(title: "", message: "Connected to internet", preferredStyle: .Alert)

        let OKAction = UIAlertAction(title: "OK", style: .Default) { (action:UIAlertAction!) in
            print("you have pressed OK button");
        }
        alertController.addAction(OKAction)

        self.presentViewController(alertController, animated: true, completion:nil)
   }
   else {  
       print(self.isConnectedToNetwork())
       // isConnectedToNetwork == false
       // It comes here when its not connected to network      
     let alertController = UIAlertController(title: "", message: "Not able to connect to internet", preferredStyle: .Alert)

        let OKAction = UIAlertAction(title: "OK", style: .Default) { (action:UIAlertAction!) in
            print("you have pressed OK button");
        }
        alertController.addAction(OKAction)

        self.presentViewController(alertController, animated: true, completion:nil)

   }

Hope this might be helpful

Karlos
  • 1,653
  • 18
  • 36
  • I tested it on a physical iPhone 6, it doesn't work. I turned the cellular data off and it worked, you got any idea about this? it's working when the 4g is off. – suisied Oct 09 '15 at 10:22
  • I have updated the answer. You will get the message "Not able to connect to internet" when 4g/3g/2g/wifi is 'OFF' and if all of the above is 'ON' then you will get prompt "Connected to internet". – Karlos Oct 09 '15 at 10:36
  • I think u just added conditionals with alertview and not alter the function. It only works with wireless connection, not detect whenver the 4g is out of service. – suisied Oct 09 '15 at 11:28
1

// Traduction to Swift 3.0

import SystemConfiguration

func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)
    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
            SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
        }
    }
    var flags = SCNetworkReachabilityFlags()

    if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
        return false }
    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    return (isReachable && !needsConnection)

}
  • 1
    Hi, welcome to stackoverflow. Please describe the answers more. Clear answer will help people understand what you mean and will increase the chance of selecting as an answer – Ashkan S Sep 24 '16 at 12:18
0

//Traduction to Swift 3.0 for the rest of the example

    if self.isConnectedToNetwork() {
        print(self.isConnectedToNetwork())
        // isConnectedToNetwork == true
        // It comes here when its connected to network
        let alertController = UIAlertController(title: "", message: "Connected to internet", preferredStyle: .alert)

        let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
            print("you have pressed OK button");
        }
        alertController.addAction(OKAction)

        self.present(alertController, animated: true, completion:nil)
    }
    else {
        print(self.isConnectedToNetwork())
        // isConnectedToNetwork == false
        // It comes here when its not connected to network
        let alertController = UIAlertController(title: "", message: "Not able to connect to internet", preferredStyle: .alert)

        let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
            print("you have pressed OK button");
        }
        alertController.addAction(OKAction)

        self.present(alertController, animated: true, completion:nil)

    }
JLanders
  • 101
  • 2
  • 11