0

我需要找出是否有网络服务器(有时在 http,有时在 https)正在监听。我更愿意同步进行,并有一个小的超时,例如 2-3 秒。

正确的方法是什么?我需要向后兼容 iOS 5。

更新:我需要在没有外部库的情况下做到这一点。

4

1 回答 1

3

由于 OP 不能使用外部库,因此实现NSURLConnectionDelegate并使用:

- (void)testUrl:(NSString *)url
{
    // Create the request.
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url]
                                              cachePolicy:NSURLRequestReloadIgnoringCacheData
                                          timeoutInterval:3.0];

    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
    int responseStatusCode = [httpResponse statusCode];

    NSLog(@"GOT STATUS CODE: %d", responseStatusCode);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Done!");
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
于 2013-04-30T17:53:36.160 回答