IT虾米网

iphone判断网络链接是否正常的代码

developer 2018年06月23日 手机开发 1018 0
+(BOOL)connectedToNetwork{ 
    struct sockaddr_in zeroAddress; 
    bzero(&zeroAddress;, sizeof(zeroAddress)); 
    zeroAddress.sin_len = sizeof(zeroAddress); 
    zeroAddress.sin_family = AF_INET; 
       
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress;); 
    SCNetworkReachabilityFlags flags; 
       
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags;); 
    CFRelease(defaultRouteReachability); 
       
    if (!didRetrieveFlags) 
    { 
        NSLog(@"Error. Could not recover network reachability flags"); 
        return NO; 
    } 
       
    BOOL isReachable = flags & kSCNetworkFlagsReachable; 
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired; 
    return (isReachable && !needsConnection) ? YES : NO; 
}

评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!