检查URL中特定页面的可达性

JAH*_*lia 7 iphone cocoa-touch objective-c reachability ios

在我阅读了这个问题的答案之后,我发现使用reachabilityWithHostName不能用于这样的URL:mySite.com/service.asmx是否有使用reachabilityWithHostName或任何reachability类方法检查对此URL的可达性?

非常感谢提前.

gai*_*ige 18

Reachability类,-reachabilityWithHostname:旨在成为一种快速,快速,快速的机制,用于确定您是否具有与主机的基本网络连接.如果您需要验证是否可以下载特定的URL,则需要查看使用NSURLConnection以检索URL的内容以验证它是否真正可用.

根据您是需要在前台还是后台执行此操作,您可以使用简单但阻塞:

+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
Run Code Online (Sandbox Code Playgroud)

或者您可以使用更复杂的方法来创建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];
Run Code Online (Sandbox Code Playgroud)

如果你收到一个非零的myData,你就有了某种连接. responseerror告诉你服务器响应了你(在响应的情况下,如果你收到一个非零的myData)或者发生了什么样的错误,在nil myData的情况下.

对于非平凡的案例,您可以从Apple的使用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) {
            // we are probably reachable, check the response
            reachable=YES;
      } else {
            // we are probably not reachable, check the error:
            reachable=NO;
      }

      // now call ourselves back on the main thread
      dispatch_async( dispatch_get_main_queue(), ^{
            [self setReachability: reachable];
      });
 });
Run Code Online (Sandbox Code Playgroud)


fbe*_*rdo 6

如果要检查URL的可访问性(通常使用的是对主机名),只需使用NSURLConnection执行HEAD请求.