The Reachability and -reachabilityWithHostname: designed to provide a quick and fault-tolerant mechanism for determining if you have a basic network connection to a host. If you need to verify that a specific URL can be downloaded, you need to use NSURLConnection to retrieve the contents of the URL to ensure that it is indeed accessible.
Depending on whether you need to do this in the foreground or in the background, you can use simple-lock:
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
or you can use the more sophisticated method of creating an NSURLConnection object by setting the delegate to receive answers and wait for these answers to appear.
For a simple case:
NSURL *myURL = [NSURL URLWithString: @"http://example.com/service.asmx"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: myURL]; [request setHTTPMethod: @"HEAD"]; NSURLResponse *response; NSError *error; NSData *myData = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error];
If you get non-nil myData back, you have some kind of connectivity. response and error will tell you that the server answered you (in case of a response and if you received a non-nil myData) or what error occurred in the case of nil myData.
In a non-trivial case, you can get a good guide from Apple Using NSURLConnection .
If you do not want to stop the foreground process, you can do this in two different ways. The above documentation will provide information on how to implement a delegate, etc. However, a simpler implementation would be to use GCD to send a synchronous request in the background thread, and then report itself to the main thread when you are done.
Something like that:
NSURL *myURL = [NSURL URLWithString: @"http://example.com/service.asmx"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: myURL]; [request setHTTPMethod: @"HEAD"]; dispatch_async( dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_BACKGROUND, NULL), ^{ NSURLResponse *response; NSError *error; NSData *myData = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error]; BOOL reachable; if (myData) {
gaige
source share