检查具有可达性的网络连接 - IsWWAN 标志始终 'false'

Checking for Network connection with Reachability - IsWWAN flag always 'false'

我的应用程序中有一个新闻源,它需要互联网连接,作为其中的一部分,我想要一个简单的连接检查,这样如果用户离线,他们就会收到一条警告消息。我有 90% 的工作正常,但是当您使用移动网络(即蜂窝网络,而不是 WiFi)时,下面的代码根本不起作用。

IsWWAN 标志似乎总是返回 false - 但我不知道为什么?

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([=11=]))
    }

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

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

    return ((isReachable || isWan) && !needsConnection)
  }
}

我看到有许多第 3 方版本的 Reachability 提供回调、通知等功能;但是我发现的一切都太复杂了,无法满足我的需要;我还没有找到解释为什么 IsWWAN 从不 returns 而 WiFi 关闭而移动网络打开的原因。

我在以下问题中找到了 Reachability class 的不同版本,它已解决此问题。

public class Reachability {
class 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([=10=]))
    }
    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)
   }
}