判断有无网络

时间:2021-10-05 16:16:52

#pragma mark  网络判断

-(BOOL)requestBeforeJudgeConnect

{

    struct sockaddr zeroAddress;

    bzero(&zeroAddress, sizeof(zeroAddress));

    zeroAddress.sa_len = sizeof(zeroAddress);

    zeroAddress.sa_family = AF_INET;

    SCNetworkReachabilityRef defaultRouteReachability =

    SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);

    SCNetworkReachabilityFlags flags;

    BOOL didRetrieveFlags =

    SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);

    CFRelease(defaultRouteReachability);

    if (!didRetrieveFlags) {

        printf("Error. Count not recover network reachability flags\n");

        return NO;

    }

    BOOL isReachable = flags & kSCNetworkFlagsReachable;

    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;

    BOOL isNetworkEnable  =(isReachable && !needsConnection) ? YES : NO;

    dispatch_async(dispatch_get_main_queue(), ^{

        [UIApplication sharedApplication].networkActivityIndicatorVisible =isNetworkEnable;/*  网络指示器的状态: 有网络 : 开  没有网络: 关  */

    });

    return isNetworkEnable;

}