在iOS上检查互联网连接会引发错误

时间:2015-01-23 19:20:00

标签: ios swift reachability internet-connection

我已在我的应用中实施了Reachability来检查互联网连接。问题是,当我调用函数Reachability.isConnectedToNetwork()时,它会在EXC_BAD_ACCESS

处抛出错误if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0

我怀疑问题出在SCNetworkReachabilityGetFlagswithUnsafePointer(&zeroAddress),但无法调试问题究竟是什么。

修改

以下是我尝试过的代码......

public class Reachability
{
    public 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
    }
}

1 个答案:

答案 0 :(得分:0)

尝试这样简单的事情:

#import "Reachability.h"

- (BOOL)connected
{
    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus networkStatus = [reachability currentReachabilityStatus];
    return networkStatus != NotReachable;
}