如何反复检查互联网连接?

How to check for internet connection repeatedly?

我正在使用 Swift 和 Parse 构建应用程序。在几个不同的 View Controllers 中,我使用 Parse 来保存和查看对象。但是,如果我必须有互联网连接才能访问 Parse。目前,我开发了以下方法来检查互联网:

    let url = NSURL(string: "http://myeighthours.com/")

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) -> Void in

        print(data)
        print(response)
        print(error)

        if let _ = data {

            UIApplication.sharedApplication().endIgnoringInteractionEvents()
            self.activityIndicator.stopAnimating()

            //Success


        } else {


            UIApplication.sharedApplication().endIgnoringInteractionEvents()
            self.activityIndicator.stopAnimating()

            //Failed

        }

    }

    task.resume()

现在这是一个单独的 View Controller。如果我要持续检查互联网,每次尝试访问 Parse 时,我都必须在所有视图控制器中使用此代码。这将是非常乏味和低效的。另外,我必须 1. 创建一个到单独的 "No Internet Connection" View Controller 的 segue,或者 2. 向每个 View Controller 添加一个按钮说 "No Internet Connection. Tap to retry"。如果我关闭互联网连接并 运行 应用程序,它只会停留在那里加载。我在调试日志中收到此错误消息:

2015-12-29 12:43:19.700 MYAPPNAME[975:354550] [Error]: The Internet connection appears to be offline. (Code: 100, Version: 1.7.5)
2015-12-29 12:43:19.700 MYAPPNAME[975:354550] [Error]: Network connection failed. Making attempt 2 after sleeping for 1.958450 seconds.
2015-12-29 12:43:21.854 MYAPPNAME[975:354549] [Error]: The Internet connection appears to be offline. (Code: 100, Version: 1.7.5)
2015-12-29 12:43:21.855 MYAPPNAME[975:354549] [Error]: Network connection failed. Making attempt 3 after sleeping for 3.916899 seconds.
2015-12-29 12:43:26.132 MYAPPNAME[975:354549] [Error]: The Internet connection appears to be offline. (Code: 100, Version: 1.7.5)
2015-12-29 12:43:26.133 MYAPPNAME[975:354549] [Error]: Network connection failed. Making attempt 4 after sleeping for 7.833799 seconds.

重复检查互联网连接的最有效方法是什么?感谢您的帮助。

#import <SystemConfiguration/SCNetworkReachability.h>

一旦您检测到无法访问 Internet 以持续检查连接性,请通过 NSTimer 调用 isNetworkReachable 方法...计时器重复持续时间应为 2-3 second.Also您的 NStimer 实例应该是全局的,而不是在每个视图控制器中

+(BOOL)isNetworkReachable
{
    SCNetworkReachabilityFlags flags;
    SCNetworkReachabilityRef address;
    address = SCNetworkReachabilityCreateWithName(NULL, "www.google.com" );
    Boolean success = SCNetworkReachabilityGetFlags(address, &flags);
    CFRelease(address);

    bool canReach = success
    && !(flags & kSCNetworkReachabilityFlagsConnectionRequired)
    && (flags & kSCNetworkReachabilityFlagsReachable);

    return canReach;
}

Best way to check for internet connection works and tested on Swift 2.0

1) 创建一个新的 swift 文件 connection.swift 并在下面包含此代码

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(kCFAllocatorDefault, UnsafePointer([=10=]))
                }

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

                let isReachable = flags == .Reachable
                let needsConnection = flags == .ConnectionRequired

                return isReachable && !needsConnection

            }
        }

You can use this method anywhere

 if Reachability.isConnectedToNetwork() == true {
                println("Internet connection OK")
            } else {
                println("Internet connection FAILED")
            }
            If the user is not connected to the internet, you may want to show them an alert dialog to notify them.
            if Reachability.isConnectedToNetwork() == true {
                println("Internet connection OK")
            } else {
                println("Internet connection FAILED")
                var alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK")
                alert.show()
        }

Took idea from

https://github.com/Isuru-Nanayakkara/Reach