How to check network status in iphone app?

混江龙づ霸主 提交于 2019-12-03 17:11:04

I suggest to make use of Apple's Reachability class. Here is a sample App by Apple.

The Reachability sample application demonstrates how to use the SystemConfiguration framework to monitor the network state of an iPhone or iPod touch. In particular, it demonstrates how to know when IP can be routed and when traffic will be routed through a Wireless Wide Area Network (WWAN) interface such as EDGE or 3G.

I personally use the following:

typedef enum
{
    NoConnection = 0,
    WiFiConnected,
    WWANConnected
} NetworkStatus;

NetworkStatus getNetworkStatus ( )
{
    struct sockaddr_in nullAddress;

    bzero(&nullAddress, sizeof(nullAddress));
    nullAddress.sin_len = sizeof(nullAddress);
    nullAddress.sin_family = AF_INET;

    SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*) &nullAddress);

    SCNetworkReachabilityFlags flags;
    SCNetworkReachabilityGetFlags(ref, &flags);

    if (!(flags & kSCNetworkReachabilityFlagsReachable))
        return NoConnection;

    if (!(flags & kSCNetworkReachabilityFlagsConnectionRequired))
        return WiFiConnected;

    if (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ||
        (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic)) &&
        !(flags & kSCNetworkReachabilityFlagsInterventionRequired))
        return WiFiConnected;

    if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
        return WWANConnected;

    return NoConnection;
}

I forget exactly where, but there's an example in the SDK somewhere that this is based on.

EDIT: looks like Nick found it... :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!