如何检查应用程序是否已连接到Internet

时间:2015-10-08 02:29:03

标签: ios swift2 reachability

我希望此课程推送或显示alertView,表示它未连接到互联网

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
}
}

这是我在mainViewcontroller(初始)

中的声明
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 

它没有任何推动力。它显示尝试2睡眠为4.34324

3 个答案:

答案 0 :(得分:2)

尝试此操作以检查设备的网络连接

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)
   }

在您的函数中添加以下代码以检查网络是否可访问并获取警报

   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)

   }

希望这可能会有所帮助

答案 1 :(得分:1)

//转换到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)

}

答案 2 :(得分:0)

//为示例的其余部分转换到Swift 3.0

    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)

    }