You can use a custom NSURLProtocol
that will intercept all your network calls.
That's exactly what I do in my OHHTTPStubs
library to stub network requests (my library use then private API to simulate a network response, but in your case if you don't need to fake a response you can avoid these calls to the private API and use this technique in production code)
[EDIT] Since this answer, OHHTTPStubs
has been updated and don't use any private API anymore, so you can use it even in production code. See my EDIT below at the end of this answer for some code example.
@interface BlockAllRequestsProtocol : NSURLProtocol
@end
@implementation BlockAllRequestsProtocol
+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
return YES; // Intercept all outgoing requests, whatever the URL scheme
// (you can adapt this at your convenience of course if you need to block only specific requests)
}
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { return request; }
- (NSCachedURLResponse *)cachedResponse { return nil; }
- (void)startLoading
{
// For every request, emit "didFailWithError:" with an NSError to reflect the network blocking state
id<NSURLProtocolClient> client = [self client];
NSError* error = [NSError errorWithDomain:NSURLErrorDomain
code:kCFURLErrorNotConnectedToInternet // = -1009 = error code when network is down
userInfo:@{ NSLocalizedDescriptionKey:@"All network requests are blocked by the application"}];
[client URLProtocol:self didFailWithError:error];
}
- (void)stopLoading { }
@end
And then to install this protocol and block all your network requests:
[NSURLProtocol registerClass:[BlockAllRequestsProtocol class]];
And to later uninstall it and let your network requests hit the real world:
[NSURLProtocol unregisterClass:[BlockAllRequestsProtocol class]];
[EDIT] Since my answer, I've updated my library which does not use any private API anymore. So anyone can use OHHTTPStubs
directly, even for the usage you need, like this:
[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest* request) {
return YES; // In your case, you want to prevent ALL requests to hit the real world
} withStubResponse:^OHHTTPStubsResponse*(NSURLRequest* request) {
NSError* noNetworkError = [NSError errorWithDomain:NSURLErrorDomain
code:kCFURLErrorNotConnectedToInternet userInfo:nil];
return [OHHTTPStubsResponse responseWithError:noNetworkError];
}];