iOS 判断网络是否连接

释放双眼,带上耳机,听听看~!
//判断网络是否连接
+ (BOOL) connectedToNetwork
{
    //创建零地址,0.0.0.0的地址表示查询本机的网络连接状态
    struct sockaddr_in zeroAddress;            //struct用来向方法中传递复杂的参数(把参数当作对象,这样便于扩展)
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    //获得连接的标志
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    //如果不能获取连接标志,则不能连接网络,直接返回
    if (!didRetrieveFlags)
    {
        return NO;
    }
    //根据获得的连接标志进行判断
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    BOOL isWWAN = flags & kSCNetworkReachabilityFlagsIsWWAN;
    return (isReachable && (!needsConnection || isWWAN)) ? YES : NO;
}

 

人已赞赏
iOS文章

iOS __weak typeof(self)weakSelf = self;的解释和使用

2019-11-17 19:40:14

iOS文章

iOS UIDevice之获取设备信息

2019-11-18 10:48:12

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索