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

标签 ios objective-c swift iphone reachability

在我阅读了 this question 的答案后我发现使用 reachabilityWithHostName 不适用于这样的 URL:mySite.com/service.asmx ,无论如何要检查此 URL 的可达性使用 reachabilityWithHostName 或任何 reachability 类方法?

非常感谢。

最佳答案

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

根据您是需要在前台还是后台执行此操作,您可以使用 simple-but-blocking:

+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error

或者您可以使用更复杂的方法创建一个 NSURLConnection 对象,设置一个委托(delegate)来接收响应并等待这些响应的到来。

对于简单的情况:

 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,你就有了某种连接。 responseerror 将告诉您服务器对您的响应(在响应的情况下并且如果您收到非零 myData)或发生了何种错误,在myData 为零的情况。

对于非平凡的情况,您可以从 Apple 的 Using NSURLConnection 获得很好的指导。 .

如果你不想停止你的前台进程,你可以用两种不同的方式来做到这一点。上述文档将提供有关如何实现委托(delegate)等的信息。但是,更简单的实现方式是使用 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];
      });
 });

关于ios - 检查 URL 中特定页面的可达性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9616914/

相关文章:

iphone - 将文件从 Mac/PC 传输到 iPhone App Document 文件夹

ios - iPhone 可以充当 NFC 标签吗?

ios - Realm 迁移枚举无法执行

objective-c - 我怎样才能在 Objective-C 中制作一个可以在 Storyboard 中的多个 View 中使用的通用控件?

ios - 为什么我使用 Swift 时屏幕截图模糊?

objective-c - 创建一个没有 Nib 的自定义 NSViewController

ios - 选择 UITableView 中所有行的更简单方法

iphone - 在 Resources 文件夹下添加 iOS 图标和启动图像

ios - Swift 只允许选择一个单元格

ios - CNContact 显示名称 objective-c /swift