Reputation: 24481
Normally, in my iOS Applications that use quite a lot of HTTP requests to communicate with the server, I add an NSBlockOperation to the app's global NSOperationQueue, and then suspend and enable the queue when the application detects a change in internet connection status thus saving any requests currently in the queue until the queue is unsuspended. However, I am not completely sure that in this way, any operations that are currently running will be stopped, and then re-added to the top of the queue.
My question is: are there any better ways to deal with a change in the network status when you are working with HTTP Requests to a remote server i.e. in pausing, resuming, cancelling requests etc...
Upvotes: 6
Views: 1374
Reputation: 6969
As Luke suggests, Apple sample is best to handle this. But I would also like to address your need for change detection in network connection. This is handled by observing the notification named kReachabilityChangedNotification.
In other words, your view controller or delegate code must have following piece in order to handle network reachability (read "connectivity") changes:
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
And
//Called by Reachability whenever status changes.
- (void) reachabilityChanged: (NSNotification* )note
{
Reachability* curReach = [note object];
//TODO: Your specific handling.
}
Upvotes: 0
Reputation: 14128
You can use the Reachability class to detect when network status changes to avoid sending requests. This is based on, and updated from, some sample code provided by Apple. This will let you know when the internet connection changes without polling.
As far as I know this is the best way to detect network availability. You'll get an instant notification when the network becomes available again. I believe it even tells you what kind of connection is available (WiFi or Cellular).
If the connection drops while making the request, you'll have to handle that condition as you currently are.
Upvotes: 2
Reputation: 1368
Transactions are just for this purpose. You need to make your ws calls atomic, that is, you start a transaction, make your call, get the response and commit the transaction. Then you can be sure that your task is completed.
In other case, you are again starting a transaction, making your ws call, ws call fails and you can' t get response, for whatever reason, and you rollback your transaction and log/report this situation. You just need to make sure if you really can' t afford missing ws calls.
Upvotes: 0
Reputation: 1155
Just my thoughts - you should add cancellation to your operations(manually) like here. When you detect network status changes(no connection), you can cancel current operations, pause queue, notify some manager so it can reschedule operations. When network becomes available, resume queue.
Upvotes: 0