我可以阻止特定时刻的networking访问吗?

编写一个iOS应用程序,我neet让用户select阻止此应用程序的networking访问只。 在代码中可以这样做吗?

意味着每一个由代码的任何部分(包括静态库)产生的调用都应该在那个特定的时刻被阻塞。

您可以使用自定义NSURLProtocol来拦截您的所有networking电话。

这正是我在我的OHHTTPStubs库中存储networking请求所做的事情(我的库使用私有API来模拟networking响应,但在您的情况下,如果您不需要伪造响应,则可以避免这些对私有API的调用,在生产代码中使用这种技术)

[编辑]由于这个答案, OHHTTPStubs已经更新,不再使用任何私人API,所以你甚至可以在生产代码中使用它。 对于某些代码示例,请参阅下面的“编辑”。


 @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 

然后安装此协议并阻止您的所有networking请求:

 [NSURLProtocol registerClass:[BlockAllRequestsProtocol class]]; 

然后卸载它,让您的networking请求打到现实世界:

 [NSURLProtocol unregisterClass:[BlockAllRequestsProtocol class]]; 

[编辑]由于我的答案,我已经更新我的图书馆不再使用任何私人API了。 所以任何人都可以直接使用OHHTTPStubs ,即使是你需要的用法,就像这样:

 [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]; }]; 

我不认为你可以使networking连接阻塞progamatically

工作

保持一个布尔variables阻止networking。检查每个networking调用variables上的值。如果块设置为是不要调用任何Web服务。

我正在使用一个小应用程序库来对应用程序中的每一个networking调用进行networking分析,无论它是你自己的代码还是第三方库。

它是封闭的源码,但从我偶尔看到的堆栈跟踪中看到,它们是CFNetwork类中的方法混搭方法。 这些都是相当低级别的networking类,将被更高层的apis使用,比如NSURLConnection(这只是我的假设)。

所以我会先看看那里