【问题标题】:No Internet Connection Even Connected Iphone App即使连接了 Iphone 应用程序也没有互联网连接
【发布时间】:2017-03-14 17:00:32
【问题描述】:

我已经为 iphone 和 ipad 制作了一些使用 xcode7 (2.3) (Swift) 的应用程序,一切正常,但我的可达性存在一个主要问题,它显示“没有互联网连接”即使我通过蜂窝数据连接到互联网但是在wifi上它工作正常..

Webview 仍然在后台加载,但是前面有错误“No Internet Connection Found”,所以用户将关闭我的应用程序,因为他们会看到错误..

请帮帮我。

这是我的代码:

覆盖 func viewDidAppear(animated: 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)

    }

}

这是我的可达性文件

导入基础 导入系统配置

公共类可达性{

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

}

}

【问题讨论】:

    标签: iphone xcode webview reachability cellular-network


    【解决方案1】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 2015-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多