我想检查一下我是否可以在iOS上使用Cocoa Touch库或在macOS上使用Cocoa库连接互联网。

我想出了一个方法来做这个使用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),如果是这样,有什么更好的方法来实现这一点?


当前回答

Alamofire

我知道这个问题是要求Coca Touch解决方案,但我想为搜索检查iOS上的互联网连接的人提供一个解决方案,在这里将有一个更多的选择。

如果您已经在使用Alamofire,以下是您可以从中受益的内容。

你可以将以下类添加到你的应用程序中,并调用MNNetworkUtils.main.isConnected()来获得一个关于它是否连接的布尔值。

#import Alamofire

class MNNetworkUtils {
  static let main = MNNetworkUtils()
  init() {
    manager = NetworkReachabilityManager(host: "google.com")
    listenForReachability()
  }

  private let manager: NetworkReachabilityManager?
  private var reachable: Bool = false
  private func listenForReachability() {
    self.manager?.listener = { [unowned self] status in
      switch status {
      case .notReachable:
        self.reachable = false
      case .reachable(_), .unknown:
        self.reachable = true
      }
    }
    self.manager?.startListening()
  }

  func isConnected() -> Bool {
    return reachable
  }
}

这是一个单例类。每次,当用户连接或断开网络时,它都会覆盖self。因为我们开始在单例初始化时监听NetworkReachabilityManager。

另外,为了监视可达性,您需要提供一个主机。目前,我正在使用google.com,但如果需要,请随意更改到任何其他主机或您的主机之一。将类名和文件名更改为与项目匹配的任何名称。

其他回答

关于Reachability的iOS 5版本是darkseed/Reachability.h。不是我的!=)

当使用iOS 12或macOS v10.14 (Mojave)或更新版本时,您可以使用NWPathMonitor而不是史前可达性类。作为奖励,你可以很容易地检测到当前的网络连接类型:

import Network // Put this on top of your class

let monitor = NWPathMonitor()

monitor.pathUpdateHandler = { path in
    if path.status != .satisfied {
        // Not connected
    }
    else if path.usesInterfaceType(.cellular) {
        // Cellular 3/4/5g connection
    }
    else if path.usesInterfaceType(.wifi) {
        // Wi-Fi connection
    }
    else if path.usesInterfaceType(.wiredEthernet) {
        // Ethernet connection
    }
}

monitor.start(queue: DispatchQueue.global(qos: .background))

更多信息请访问:https://developer.apple.com/documentation/network/nwpathmonitor

使用http://huytd.github.io/datatify/。这比自己添加库和编写代码要容易得多。

这曾经是正确的答案,但现在已经过时了,因为你应该订阅通知以获得可访问性。这个方法同步检查:


你可以使用苹果的Reachability类。它还可以让你检查是否启用了Wi-Fi:

Reachability* reachability = [Reachability sharedReachability];
[reachability setHostName:@"www.example.com"];    // Set your host name here
NetworkStatus remoteHostStatus = [reachability remoteHostStatus];

if (remoteHostStatus == NotReachable) { }
else if (remoteHostStatus == ReachableViaWiFiNetwork) { }
else if (remoteHostStatus == ReachableViaCarrierDataNetwork) { }

Reachability类并没有随SDK一起发布,而是作为这个Apple示例应用程序的一部分。只需下载它,并复制Reachability.h/m到您的项目。另外,您必须将SystemConfiguration框架添加到您的项目中。

苹果提供了一个示例应用程序,它正是这样做的:

可达性