Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking For Internet Connectivity in Objective C

I've been working through the Stanford iPhone Coding course and currently hooking into the Twitter API. What I'd like to do is accurately handle two error conditions: One for when the username is invalid, and another for when the device is not currently connected to the internet. Unfortunately, as it stands, the best I can surmise is whether or not the return from the API is nil or not - which is the case for both conditions.

What I'm looking for is a line or two of code that can check for a connection before attempting any fetch of remote data. I could sift through the Apple documentation but I figured: Why not put the question to you guys for my benefit and perhaps that of others?

Additional info: Using Objective-C and the iPhone SDK in XCode.

like image 722
lewsid Avatar asked Jan 25 '09 15:01

lewsid


Video Answer


2 Answers

Take a look at Apple's sample code. The Reachability project shows how to detect a connection.

http://developer.apple.com/iphone/library/samplecode/Reachability/index.html

like image 115
August Avatar answered Oct 15 '22 06:10

August


That code works, but doesn't always create the desired result.

The way that the TCP stack on the iPhone works is very different from what should be expected. With the "Reachability" code, sometimes a network connection will be present, but will not be reliably detected. However, launching MobileSafari then reattempting to check connectivity with "Reachability" code will result in the correct result.

The way that I have found most effective in determining network connectivity is to run a NSURLConnection check when the application loads, in a separate thread. Make a call to a URL that you know will return something like "Yes" (i.e. HTML file on your server or something). Then check to be sure the returned result is equal to the static text. That way, you know that the NSURLConnection stack is reaching out properly, as opposed to the "Reachability" code that does not quite work consistently.

like image 44
Jason Avatar answered Oct 15 '22 05:10

Jason