小编典典

如何在 iOS 或 macOS 上检查活动的 Internet 连接?

all

我想查看是否在 iOS 上使用Cocoa Touch库或在
macOS 上使用Cocoa库连接到 Internet。

我想出了一种使用NSURL.
我这样做的方式似乎有点不可靠(因为即使谷歌有一天可能会失败并且依赖第三方似乎很糟糕),虽然如果谷歌没有回应,我可以查看其他网站的回应,它对我的应用程序来说似乎是浪费和不必要的开销。

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

我做错了什么(更不用说stringWithContentsOfURL在 iOS 3.0 和 macOS 10.4
中已弃用),如果是这样,有什么更好的方法来做到这一点?


阅读 107

收藏
2022-02-25

共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”)
    }


Objective-C

  1. SystemConfiguration框架添加到项目中,但不必担心将其包含在任何地方

  2. 将 Tony Million 的Reachability.h和版本添加Reachability.m到项目中(可在此处找到:https ://github.com/tonymillion/Reachability )

  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];
      }

重要说明:
该类Reachability是项目中最常用的类之一,因此您可能会遇到与其他项目的命名冲突。如果发生这种情况,您必须将其中一对Reachability.hReachability.m文件重命名为其他名称才能解决问题。

注意: 您使用的域无关紧要。它只是测试通往任何域的网关。

2022-02-25