我已经为iphone和ipad制作了一些xcode7(2.3)(Swift)的应用程序,一切正常,但我的可达性有一个主要问题,它说"没有互联网连接"即使我通过蜂窝数据连接到互联网,但在wifi上它工作正常..
Webview仍然在后台加载但是有错误"没有找到Internet连接"在前面,所以用户将关闭我的应用程序,因为他们将看到错误..
请帮帮我吧..
这是我的代码:
覆盖func viewDidAppear(动画:Bool){
if Reachability.isConnectedToNetwork() == true {
print("Internet connection OK")
} else {
print("Internet connection FAILED")
let ViewController = UIAlertController(title: "Error!", message: "No Internet Connection Found", preferredStyle: .Alert)
let alertAction = UIAlertAction(title: "Dismiss", style: .Destructive) { (action) in
print("Dismiss button tapped!")
}
ViewController.addAction(alertAction)
presentViewController(ViewController, animated: true, completion: nil)
}
}
这是我的可达性文件
导入基金会 import SystemConfiguration
公共课程可达性{
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
}
}
答案 0 :(得分:0)
试试这个
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return false
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}