我试图通过用swift 2.0编写的Reachability.swift类来检查互联网连接状态。这是类代码:
import UIKit
import Foundation
import SystemConfiguration
public class Reachability: NSObject {
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)
}
}
我的问题是这个;当我连接到蜂窝网络时,这个类无法识别它,这意味着isConnectedToNetwork()方法在我的iPhone 5设备上返回false,而不是模拟器。那可能是什么情况?请蚂蚁帮助,不仅仅是... ...
答案 0 :(得分:1)
除了Reachable和ConnectionRequired,您还需要检查这一点。
let isWan = flags = .IsWWAN
如果设置了Reachable或IsWWAN,则表示您已连接到网络。 IsWWAN告诉您是否可以通过蜂窝连接(如EDGE或GPRS)访问指定的节点名称或地址。