1

ユーザーがボタンを押したとき、3 秒前に接続されたかどうかではなく、その瞬間にデバイスがインターネットに接続されているかどうかを知る必要があります。到達可能性 (tonymillion) 通知機能は、ネットワークの到達可能性が変化した後、更新するのにそれくらいの時間がかかります。

以下の方法で実際のアクセスをリアルタイムで確認できるのではないかと考えました。

if (!([[Reachability reachabilityWithHostname:@"www.google.com"] currentReachabilityStatus] == NotReachable)) NSLog(@"reachable");
if ([[Reachability reachabilityWithHostname:@"www.google.com"] currentReachabilityStatus] == NotReachable) NSLog(@"not reachable");

しかし、結果は、実際currentReachabilityStatusにはインターネット アクセスをチェックしていないことを示しています。約 3 秒の遅延で更新される同じフラグのみをチェックします。

その場で実際にネットワーク アクセスを確認する効率的な方法は何ですか?

4

2 に答える 2

1

到達可能性ステータスにオブザーバーを配置しようとしましたか?

以前使用していた Reachabilty 拡張機能 ( NPReachability ) を使用すると、ステータスで KVO を使用できます。

于 2013-08-09T17:36:22.460 に答える
1

上記のコメントで希望したように、「HEAD」リクエストを使用したソリューションを次に示します。

  1. クラスを NSURLConnectionDelegateに準拠させます。
  2. connection:didReceiveResponse:デリゲート メソッドを実装する
  3. connection:didFailWithError:必要に応じてデリゲート メソッドを実装する

したがって、セットアップは次のようになります。

あなたのクラス.m

@interface YourClass () <NSURLConnectionDelegate>
@property (strong, nonatomic) NSURLConnection *headerConnection;
@end

@implementation YourClass

- (void)viewDidLoad {
    // You can do this in whatever method you want
    NSMutableURLRequest *headerRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10.0];
    headerRequest.HTTPMethod = @"HEAD";
    self.headerConnection = [[NSURLConnection alloc] initWithRequest:headerRequest delegate:self];
}

#pragma mark - NSURLConnectionDelegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    if (connection == self.headerConnection) {
        // Handle the case that you have Internet; if you receive a response you are definitely connected to the Internet
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // Note: Check the error using `error.localizedDescription` for getting the reason of failing
    NSLog(@"Failed: %@", error.localizedDescription);
}
于 2013-08-09T21:22:05.150 に答える