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

时间:2015-12-29 07:17:34

标签: ios xcode swift parse-platform internet-connection

我正在使用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.创建一个单独的"无互联网连接"查看控制器,或2.向每个视图控制器添加一个按钮,说“没有Internet连接”。点按即可重试"。如果我关闭我的互联网连接并运行应用程序,它只是在那里加载。我在调试日志中收到此错误消息:

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.

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

2 个答案:

答案 0 :(得分:1)

  

检查互联网连接的最佳方法是在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($0))
                }

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

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

                return isReachable && !needsConnection

            }
        }
  

您可以在任何地方使用此方法

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

中提出想法

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

答案 1 :(得分:-2)

#import <SystemConfiguration/SCNetworkReachability.h>
一旦您检测到无法访问Internet以连续检查连接,

调用NSTimer的isNetworkReachable方法...计时器重复持续时间应为2-3秒。此外,您的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;
}