有WiFi网络更改的NSNotificationCenter通知吗? [英] Is there a NSNotificationCenter Notification for WiFi network changes?

查看:171
本文介绍了有WiFi网络更改的NSNotificationCenter通知吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想订阅我的Cocoa应用程式中的WiFi网路变更,但我无法找到合适的活动来订阅。

I'd like to subscribe to WiFi network changes in my Cocoa application, but I haven't been able to find an appropriate event to subscribe to.

有没有针对WiFi网络更改的NSNotificationCenter通知?

Is there an NSNotificationCenter Notification for WiFi network changes?

推荐答案

我将使用 CoreWLAN 获取列表所有WiFi接口,然后使用 SystemConfiguration 框架。

Not to my knowledge. I would use CoreWLAN to get a list of all WiFi interfaces on the system, and then monitor their status using the SystemConfiguration framework.

这是一个命令行示例(错误检查nicards elided,ARC required):

Here's a command-line example (error checking niceties elided, ARC required):

#import <Foundation/Foundation.h>
#import <CoreWLAN/CoreWLAN.h>
#import <SystemConfiguration/SystemConfiguration.h>

void wifi_network_changed(SCDynamicStoreRef store, CFArrayRef changedKeys, void *ctx)
{
  [(__bridge NSArray *)changedKeys enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop)
  {
    /* Extract the interface name from the changed key */
    NSString *ifName = [key componentsSeparatedByString:@"/"][3];
    CWInterface *iface = [CWInterface interfaceWithName:ifName];

    NSLog(@"%@ status changed: current ssid is %@, security is %ld",
          ifName, iface.ssid, iface.security);
  }];
}

int main(int argc, char *argv[])
{
  /* Get a list of all wifi interfaces, and build an array of SCDynamicStore keys to monitor */
  NSSet *wifiInterfaces = [CWInterface interfaceNames];
  NSMutableArray *scKeys = [[NSMutableArray alloc] init];
  [wifiInterfaces enumerateObjectsUsingBlock:^(NSString *ifName, BOOL *stop)
  {
    [scKeys addObject:
      [NSString stringWithFormat:@"State:/Network/Interface/%@/AirPort", ifName]];
  }];

  /* Connect to the dynamic store */
  SCDynamicStoreContext ctx = { 0, NULL, NULL, NULL, NULL };
  SCDynamicStoreRef store = SCDynamicStoreCreate(kCFAllocatorDefault,
                                                 CFSTR("myapp"),
                                                 wifi_network_changed,
                                                 &ctx);

  /* Start monitoring */
  SCDynamicStoreSetNotificationKeys(store,
                                    (__bridge CFArrayRef)scKeys,
                                    NULL);

  CFRunLoopSourceRef src = SCDynamicStoreCreateRunLoopSource(kCFAllocatorDefault, store, 0);
  CFRunLoopAddSource([[NSRunLoop currentRunLoop] getCFRunLoop],
                     src,
                     kCFRunLoopCommonModes);
  [[NSRunLoop currentRunLoop] run];
}

这篇关于有WiFi网络更改的NSNotificationCenter通知吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆