OSX的网络连接NSNotification

OSX的网络连接NSNotification

本文介绍了OSX的网络连接NSNotification?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

分配有效的IP地址后,我只需要有一个通知栏即可.我曾尝试通过SCReachability进行轮询,但这似乎效率很低.

I simply need to have a notification post when a valid IP address is assigned. I have tried polling via SCReachability, but that seems to be inefficient.

有什么建议吗?这看起来应该很简单,但是我一直在努力几个小时才能使所有工作正常进行.

Any suggestions? This seems like it should be simple, but I've been struggling for several hours to get anything working.

推荐答案

我知道这有点老,但所选答案并不理想.

I know this is a bit old but the selected answer is not ideal.

SCReachability API可用于了解何时可以访问特定主机.如果您只想知道何时分配了有效的IP地址(而不是通往目标IP的可行路由),则应改用SCDynamicStore * API.这些功能使您可以订阅系统的配置存储,以在某些值更改时进行通知.因此,要在IPv4地址在任何接口上更改时通知您,请执行以下操作(已删除错误检查以提高可读性)

The SCReachability API can be used to know when a particular host is reachable. If all you want to know is when a valid IP address is assigned (rather than a viable route to a target IP) then you should look at the SCDynamicStore* APIs instead.These functions allow you to subscribe to the system's configuration store for notification when certain values change.So, for notification when the IPv4 address changes on any interface you would do the following (error checking removed for readability)

  SCDynamicStoreRef dynStore;

  SCDynamicStoreContext context = {0, NULL, NULL, NULL, NULL};

  dynStore = SCDynamicStoreCreate(kCFAllocatorDefault,
                                  CFBundleGetIdentifier(CFBundleGetMainBundle()),
                                  scCallback,
                                  &context);

    const CFStringRef keys[3] = {
        CFSTR("State:/Network/Interface/.*/IPv4")
    };
    CFArrayRef watchedKeys = CFArrayCreate(kCFAllocatorDefault,
                                         (const void **)keys,
                                         1,
                                         &kCFTypeArrayCallBacks);
    if (!SCDynamicStoreSetNotificationKeys(dynStore,
                                         NULL,
                                         watchedKeys))
  {
       CFRelease(watchedKeys);
        fprintf(stderr, "SCDynamicStoreSetNotificationKeys() failed: %s", SCErrorString(SCError()));
        CFRelease(dynStore);
        dynStore = NULL;

        return -1;
    }
    CFRelease(watchedKeys);

    rlSrc = SCDynamicStoreCreateRunLoopSource(kCFAllocatorDefault, dynStore, 0);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), rlSrc, kCFRunLoopDefaultMode);
    CFRelease(rlSrc);

您将需要实现scCallback函数,该函数将在发生任何更改时被调用.另外,您还需要在某个地方调用CFRunLoopRun才能使代码运行.

You will need to imlement the scCallback function which will be called whenever there is a change. Also you'll need to call CFRunLoopRun somewhere to make the code go.

这篇关于OSX的网络连接NSNotification?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 08:05