Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reachability vs NSURLSession response to detect internet connection

I'm building out error cases for my API calls and would like to check for a condition when an internet connection in not available.

dataTaskWithRequest seems to handle this just fine and returns an NSError with code -1009 with a description of no internet connection. I doesn't have to wait for the request to time out.

In what instances would I want to use the Reachability Framework instead? Thanks

like image 745
yamski Avatar asked Feb 12 '16 17:02

yamski


People also ask

How does Nwpathmonitor check Internet connection?

You can use the function usesInterfaceType(_:) to check which interface type this network path uses. This is the most effective way to figure out if your app is connected over WiFi, cellular or ethernet. print(“It's WiFi!”)

How can I tell if Iphone is connected to Internet?

Go to Settings > Wi-Fi and make sure that Wi-Fi is on. Tap the name of your Wi-Fi network to join. A blue checkmark beside a network name means that you're connected.


1 Answers

I did a bit of research and found my answer in the Apple Docs.

The recommended best practice is to attempt the connection. If there is an issue with the connection, it gives you an NSError object that you should use to test for connectivity.

Apple recommends using Reachability only as a way to diagnose errors and further debug known issues. It seems like you should only use reachability to detect when the network comes back online after a failure.

"Always attempt to make a connection. Do not attempt to guess whether network service is available, and do not cache that determination.

If a connection fails, use the SCNetworkReachability API to help diagnose the cause of the failure."

source : https://developer.apple.com/library/ios/documentation/NetworkingInternetWeb/Conceptual/NetworkingOverview/WhyNetworkingIsHard/WhyNetworkingIsHard.html#//apple_ref/doc/uid/TP40010220-CH13-SW3

"When any task completes, the NSURLSession object calls the delegate’s URLSession:task:didCompleteWithError: method with either an error object or nil (if the task completed successfully).

If the task failed, most apps should retry the request until either the user cancels the download or the server returns an error indicating that the request will never succeed. Your app should not retry immediately, however. Instead, it should use reachability APIs to determine whether the server is reachable, and should make a new request only when it receives a notification that reachability has changed."

source:

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/NSURLSessionConcepts/NSURLSessionConcepts.html

like image 195
yamski Avatar answered Nov 07 '22 07:11

yamski