Reachability类和-reachabilityWithHostname:方法旨在快速、快速地确定您是否具有与主机的基本网络连接。如果您需要验证特定URL是否可以下载,则需要使用NSURLConnection检索URL的内容,以验证其是否真正可用。
根据您是需要在前台还是后台执行此操作,您可以使用简单但会阻塞的:
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
或者您可以使用更复杂的方法,创建一个NSURLConnection对象,设置代理以接收响应并等待这些响应的到来。
对于简单情况:
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];
如果你收到了非空的
myData
,那么你就有了某种连接。在
response
和
error
中,会告诉你服务器对你做出了什么响应(在响应的情况下,如果你收到了非空的
myData
),或者发生了什么样的错误(对于一个空的
myData
)。
对于复杂的情况,你可以从苹果公司的
使用NSURLConnection获取良好的指导。
如果你不想阻塞前台进程,可以用两种不同的方式来实现。上述文档将提供有关如何实现委托等信息。但是,更简单的实现方式是使用GCD在后台线程上发送同步请求,然后在完成时向主线程发送消息。
像这样:
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) {
reachable=YES;
} else {
reachable=NO;
}
dispatch_async( dispatch_get_main_queue(), ^{
[self setReachability: reachable];
});
});