iOS 验证是否已连接到网络

示例

迅速

import SystemConfiguration

///类有助于代码重用,以处理Internet网络连接。
class NetworkHelper {

    /**
     Verify if the device is connected to internet network.
     - returns:          true if is connected to any internet network, false if is not
     connected to any internet network.
     */
   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)
   }
}



if NetworkHelper.isConnectedToNetwork() {
    // 连接到网络
}

目标C:

我们可以在几行代码中检查网络连通性,如下所示:

-(BOOL)isConntectedToNetwork
{
    Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
    if (networkStatus == NotReachable)
    {
        NSLog(@"There IS NO internet connection");
        return false;
    } else
    {
        NSLog(@"There IS internet connection");
        return true;
    }
}