Determining network status.

Discussion in 'iOS Development' started by gojohnnyboi, Mar 14, 2009.

  1. gojohnnyboi

    gojohnnyboi Well-Known Member

    Joined:
    Jan 25, 2008
    Messages:
    3,339
    Likes Received:
    55
    How can i determine whether or not the iPhone is connected to a network or not?
  2. NolesFans

    NolesFans New Member

    Joined:
    Sep 23, 2008
    Messages:
    404
    Likes Received:
    0
    Device:
    iPod touch
    Code:
    + (BOOL)isReachableWithoutRequiringConnection:(SCNetworkReachabilityFlags)flags {
    	// kSCNetworkReachabilityFlagsReachable indicates that the specified nodename or address can
    	// be reached using the current network configuration.
    	BOOL isReachable = flags & kSCNetworkReachabilityFlagsReachable;
    	
    	// This flag indicates that the specified nodename or address can
    	// be reached using the current network configuration, but a
    	// connection must first be established.
    	//
    	// If the flag is false, we don't have a connection. But because CFNetwork
    	// automatically attempts to bring up a WWAN connection, if the WWAN reachability
    	// flag is present, a connection is not required.
    	BOOL noConnectionRequired = !(flags & kSCNetworkReachabilityFlagsConnectionRequired);
    	if (flags & kSCNetworkReachabilityFlagsIsWWAN) {
    		noConnectionRequired = YES;
    	}
    	
    	return (isReachable && noConnectionRequired) ? YES : NO;
    }
    
    + (BOOL)isNetworkAvailable {
    	struct sockaddr_in zeroAddress;
    	bzero(&zeroAddress, sizeof(zeroAddress));
    	zeroAddress.sin_len = sizeof(zeroAddress);
    	zeroAddress.sin_family = AF_INET;
    	
    	SCNetworkReachabilityRef networkReachability = 
    	SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    	
    	SCNetworkReachabilityFlags flags;
    	BOOL gotFlags = SCNetworkReachabilityGetFlags(networkReachability, &flags);
    	CFRelease(networkReachability);
    	if (!gotFlags) {
    		return NO;
    	}
    	
    	return [self isReachableWithoutRequiringConnection:flags];
    }
    You needed SystemConfiguration.framework

    #import <SystemConfiguration/SCNetworkReachability.h>
    #import <netinet/in.h>
  3. gojohnnyboi

    gojohnnyboi Well-Known Member

    Joined:
    Jan 25, 2008
    Messages:
    3,339
    Likes Received:
    55
    awesome. and is this good with the rules of the sdk?
  4. Chicken

    Chicken Retired Moderator

    Joined:
    Feb 17, 2008
    Messages:
    2,494
    Likes Received:
    7
    Device:
    iPhone 5S
    I'd expect so, as many apps see what network you're using such as the fring app, they will only let you use it on 3G or Wifi, so they have to check.

Share This Page