Check Network Status when developing networked applications for iOS

When developing iOS applications which make use of the network connection you should always first check if there is any network available. If there is not the user should be warned with some kind of pop up or alert. If sending an application which does not check for an existing connection to apple it might get rejected by them. As stated above, when downloading large data it also might be of interest to know if the user uses the cellular or the wifi connection to determine which quality the download should have.
1 answer

Checking if a network connection is available and of what kind it is.

IOS can currently check for the following configuration states: some connection available (any kind), wifi available or cell service available. There is currently no API for checking if bluetooth is available or the user is on a roaming network.

In the system configuration framework many network aware functions are made available.
Among these, SCNetworkReachabilityCreateWithAddress
checks whether an IP address is reachable or not and returns a boolean value.

Sample Code
- (BOOL) connectedToNetwork
{
// Create zero addy
struct sockaddr_in zeroAddress;
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)
{
printf("Error. Could not recover network reachability flags\n");
return NO;
}

BOOL isReachable = flags & kSCNetworkFlagsReachable;
BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
return (isReachable && !needsConnection) ? YES : NO;
}

The flags used in this method indicate both that the network is reachable (ksCNetworkFlagsReachable) and that no further connection is required (ksCNetworkFlagsConnectionRequired).
Other flags that might be used are:
ksCNetworkReachabilityFlagsIsWWAN --> This tests if the user is on a cellular network or a wifi network. When available the user is on a cellular network meaning that you might use smaller size downloads.
ksCNetworkReachabilityFlagsConnectionOnTraffic --> Specifies that addresses can be reached with the current network configuration but that a connection must first be established. Any actual traffic will initiate the connection.
ksCNetworkReachabilityFlagsIsDirect --> Tells whether the network traffic goes through a gateway or arrives directly.

To test that connectivity check you absolutely must test your application on an iPhone because it can make use of cellular and wifi networks. You should also test the flight mode on the device.