iOS または macOS でアクティブなインターネット接続を確認するにはどうすればいいですか? 質問する

iOS または macOS でアクティブなインターネット接続を確認するにはどうすればいいですか? 質問する

iOSでインターネット接続があるかどうか確認するには、ココアタッチライブラリまたはmacOSでココアライブラリ。

私は、 を使用してこれを行う方法を思いつきましたNSURL。私が行った方法は、少し信頼性が低いようです (Google でさえある日ダウンする可能性があり、サードパーティに依存するのは良くないと思われるため)。また、Google が応答しない場合は他の Web サイトからの応答を確認することはできますが、それは無駄であり、アプリケーションに不要なオーバーヘッドがかかるようです。

- (BOOL)connectedToInternet {
    NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
    return ( URLString != NULL ) ? YES : NO;
}

私が行ったことは悪いことでしょうか ( stringWithContentsOfURLiOS 3.0 および macOS 10.4 では非推奨であることは言うまでもありません)。もしそうなら、これを実現するより良い方法は何でしょうか?

ベストアンサー1

重要: このチェックは常に非同期で実行する必要があります。以下の回答の大部分は同期なので、注意しないとアプリがフリーズしてしまいます。


迅速

  1. CocoaPods または Carthage 経由でインストールします。https://github.com/ashleymills/Reachability.swift

  2. クロージャによる到達可能性のテスト

    let reachability = Reachability()!
    
    reachability.whenReachable = { reachability in
        if reachability.connection == .wifi {
            print("Reachable via WiFi")
        } else {
            print("Reachable via Cellular")
        }
    }
    
    reachability.whenUnreachable = { _ in
        print("Not reachable")
    }
    
    do {
        try reachability.startNotifier()
    } catch {
        print("Unable to start notifier")
    }
    

オブジェクティブC

  1. SystemConfigurationプロジェクトにフレームワークを追加しますが、どこにでも含める必要はありません。

  2. Tony Million のバージョンReachability.hとをReachability.mプロジェクトに追加します (こちらにあります:https://github.com/tonymillion/到達可能性

  3. インターフェースセクションを更新する

    #import "Reachability.h"
    
    // Add this to the interface in the .m file of your view controller
    @interface MyViewController ()
    {
        Reachability *internetReachableFoo;
    }
    @end
    
  4. 次に、ビューコントローラの.mファイルにこのメソッドを実装します。

    // Checks if we have an internet connection or not
    - (void)testInternetConnection
    {
        internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];
    
        // Internet is reachable
        internetReachableFoo.reachableBlock = ^(Reachability*reach)
        {
            // Update the UI on the main thread
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"Yayyy, we have the interwebs!");
            });
        };
    
        // Internet is not reachable
        internetReachableFoo.unreachableBlock = ^(Reachability*reach)
        {
            // Update the UI on the main thread
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"Someone broke the internet :(");
            });
        };
    
        [internetReachableFoo startNotifier];
    }
    

重要な注意:クラスはプロジェクトで最もよく使用されるクラスの 1 つであるため、他のプロジェクトと名前の競合が発生する可能性があります。このような場合は、ファイルファイルのペアのいずれかの名前を別の名前に変更して問題を解決するReachability必要があります。Reachability.hReachability.m

注:使用するドメインは重要ではありません。任意のドメインへのゲートウェイをテストするだけです。

おすすめ記事