OSX/Swift:在建立/恢复互联网连接时调用一个函数

时间:2022-11-02 16:53:03

What I want to do is call some code when the internet connection is established or restored.

我想做的是在建立或恢复互联网连接时调用一些代码。

I know there are solutions out there that let me test whether an internet connection is active or not, but I am wondering if there is a way for a function to be triggered by the internet connection becoming active.

我知道有一些解决方案可以让我测试internet连接是否处于活动状态,但是我想知道是否有一种方法可以让一个功能在internet连接变得活跃时被触发。

If not, what is the best workaround? Checking for a connection every x seconds? Thanks.

如果没有,最好的变通方法是什么?每隔x秒检查一次连接?谢谢。

1 个解决方案

#1


1  

The SCNetworkReachability APIs can be configured to generate notifications when the reachability status of an IP address or hostname changes. Create a SCNetworkReachabilityRef, then set a callback, and it will be called when a network change is detected.

当IP地址或主机名的可达状态发生变化时,可以配置scnetworkability api来生成通知。创建一个scnetworkclaiabilityref,然后设置一个回调,当检测到网络变化时将调用它。

#1


1  

The SCNetworkReachability APIs can be configured to generate notifications when the reachability status of an IP address or hostname changes. Create a SCNetworkReachabilityRef, then set a callback, and it will be called when a network change is detected.

当IP地址或主机名的可达状态发生变化时,可以配置scnetworkability api来生成通知。创建一个scnetworkclaiabilityref,然后设置一个回调,当检测到网络变化时将调用它。