Check Internet connection availability?

前端 未结 4 1939
悲哀的现实
悲哀的现实 2021-01-17 19:20

I just need to check the internet connection availability before start communicating with the service in my iphone App. I am using Swift 1.2 and Xcode 6 as my development en

4条回答
  •  温柔的废话
    2021-01-17 19:41

    Edit for Swift 5.x :

    import SystemConfiguration
    
    public class CheckInternet{
    
        class func Connection() -> 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(MemoryLayout.size(ofValue: zeroAddress))
            zeroAddress.sin_family = sa_family_t(AF_INET)
    
            let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
                $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
                    SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
                }
            }
    
            var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
            if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
                return false
            }
    
    
            // Working for Cellular and WIFI
            let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
            let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
            let ret = (isReachable && !needsConnection)
    
            return ret
    
    
        }
    
    }
    

提交回复
热议问题