Tutorial :how can we know iphone has got information from Internet?



Question:

i want to display activity indicator when i search from the internet.but how can i know the iphone has got response from the internet to stop animating activity indicator? is there any method?


Solution:1

Take a look at NSURLConnection's delegate methods. In particular, connection:didReceiveResponse: and connectionDidFinishLoading:

Under the connection:didReceiveResponse: delegate method you can display the network activity indicator like so:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {      [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;      //...  }  

and then hide it in connection:DidFinishLoading:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {  [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;  //...  }  

You should also hide it in connection:didFailWithError: should your connection attempt fail.


Solution:2

To handle this, I made a singleton connection manager class which will do the work of setting up and sending a url connection. It basically routes the connection through itself, intercepting the delegate calls. It retains each url connection in an array and passes back the delegate calls using a dictionary of connection > delegate.

When it receives the delegate call for the url, it messages the "real" delegate of the connection and removes the connection from the array and dictionaries.

This way you always know if there's a connection open (because the connections array is not empty) and can display the indicator. This way you can send off many connections and still guarantee that you are always displaying the indicator when there is a connection and never displaying it when there are no connections.

My implementation for this can be found on Bitbucket, it uses my own subclass to NSURLConnection which adds unique keys for each connection.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »