Alpinista
Alpinista

Reputation: 3741

Proper way to check for Network Connection in iOS

I'm using the Reachability class to monitor network connection and server availability in a couple of iPhone apps. I have the following code in my AppDelegate:

// Observe the kNetworkReachabilityChangedNotification. When that notification is posted, the
// method "reachabilityChanged" will be called. 
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];

// Start checking for reachability to myWebService.com
//Change the host name here to change the server your monitoring
hostReach = [Reachability reachabilityWithHostName: @"myWebService.com"];
[hostReach startNotifier];

internetReach = [Reachability reachabilityForInternetConnection];
[internetReach startNotifier];

wifiReach = [Reachability reachabilityForLocalWiFi];
[wifiReach startNotifier];

When I profile one of the apps (a dedicated blog reader for my companies blog) using Instruments, I see a difference of +5.9 Mb of network traffic over a one minute period when I turn on the notifiers, vs commenting those lines out.

What is the proper way to check for network connection before sending a request to a server? I probably shouldn't be monitoring the connection full time, but only when I need to know.

My other app communicates with a web service API to post pages and video, and I want to know if I have a connection to that service before attempting to post, but I want to minimize network traffic where I can.

I'd guess that this is one thing Apple looks for when approving/rejecting apps in the app store.

Upvotes: 0

Views: 1632

Answers (1)

Randall
Randall

Reputation: 14839

Instead of checking the connection before you make the request, just check for a network connection error when you do make the request. You can periodically make requests if you want to update the status of the network.

Upvotes: 1

Related Questions