美文网首页
判断是否有网络连接

判断是否有网络连接

作者: 雷霸龙 | 来源:发表于2017-04-24 20:17 被阅读40次

    调用下面方法即可判断是否有网络连接,根据[self connectedToNetwork]或![self connectedToNetwork]来判断网络连接的有无。

    // 判断是否有网络
    -(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)
        {
            printf("Error. Could not recover network reachability flags\n");
            return NO;
        }
        
        BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
        BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
        return (isReachable && !needsConnection) ? YES : NO;
    }
    

    相关文章

      网友评论

          本文标题:判断是否有网络连接

          本文链接:https://www.haomeiwen.com/subject/liapzttx.html