Check if iPhone is connected to the internet [duplicate]

泄露秘密 提交于 2019-12-19 10:07:36

问题


how I can check quickly if the iPhone is connected to internet or not, quickly...

Thanks...


回答1:


Have a look at Apple's Reachability class and this example app.




回答2:


You should try to connect to the server with what you think is an appropriate timeout. NEVER use the reachability API until you've determined that your connection attempt failed and even then only if the error you receive from NSURLConnection et. al. is one that suggests you're not connected to the network. In that case, use the Reachability API to determine when you should try again.

Merely attempting a connection may bring up a network interface that wasn't available before.




回答3:


You can check for internet connection in swift using code below:

import SystemConfiguration

class Reachability: NSObject {

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($0))
    }
    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)
}

Hope this helps!!



来源:https://stackoverflow.com/questions/6129219/check-if-iphone-is-connected-to-the-internet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!