wifi连接时的通知(OS X)

时间:2012-06-28 07:46:58

标签: objective-c macos wifi

当机场连接到ap时,我需要系统发出通知。有SystemConfiguration框架可以做到这一点吗?我无法理解systemconfigurations api文档。

2 个答案:

答案 0 :(得分:3)

您正在使用SystemConfiguration网络走上正轨,该网络提供SCNetworkReachability个功能集。你可以尝试使用

SCNetworkReachabilitySetCallback

设置一个回调,当可达性改变时将调用该回调;和

SCNetworkReachabilityScheduleWithRunLoop

在运行循环中安排可达性检查

或者您可以尝试使用基于SystemConfiguration框架构建的reachability framework(适用于MacOS和iOS),以使事情变得更加容易(更高级别)。

如果您想使用SystemConfiguration方式,请检查当前的可访问性并安装回调以通知更改(source):

- (void)checkReachability {
  NSString *server = [[NSUserDefaults standardUserDefaults] stringForKey:@"NCIDServer"];

  if (server == nil) {
    ncid_message_callback(self, [NSLocalizedString(@"No caller ID server was specified.", nil) UTF8String]);
    return;
  }

  const char *serverName = [[[server componentsSeparatedByString:@":"] objectAtIndex:0] UTF8String];
  SCNetworkReachabilityContext context = {0, (void *)self, NULL, NULL, NULL};
  networkReachability = SCNetworkReachabilityCreateWithName(NULL, serverName);

  if (networkReachability == NULL)
    goto fail;

  // If reachability information is available now, we don't get a callback later
  SCNetworkConnectionFlags flags;

  if (SCNetworkReachabilityGetFlags(networkReachability, &flags))
    networkReachabilityCallback(networkReachability, flags, self);

  if (!SCNetworkReachabilitySetCallback(networkReachability, networkReachabilityCallback, &context))
    goto fail;

  if (!SCNetworkReachabilityScheduleWithRunLoop(networkReachability, [[NSRunLoop currentRunLoop] getCFRunLoop], kCFRunLoopCommonModes))
     goto fail;
  return;

fail:
  if (networkReachability != NULL)
    CFRelease(networkReachability);

  networkReachability = NULL; //-- ivar representing current reachability

}

这是回调的一个示例:

static void networkReachabilityCallback(SCNetworkReachabilityRef target,
                SCNetworkConnectionFlags flags,
                void *object) {
  // Observed flags:
  // - nearly gone: kSCNetworkFlagsReachable alone (ignored)
  // - gone: kSCNetworkFlagsTransientConnection | kSCNetworkFlagsReachable | kSCNetworkFlagsConnectionRequired
  // - connected: kSCNetworkFlagsIsDirect | kSCNetworkFlagsReachable

  if (networkReachability == NULL)
    return;

  if ((flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired))    {

    if (isReachable) // typically receive a reachable message ~20ms before the unreachable one
    return;

    isReachable = YES;
    ncid_network_kill();
    [NSThread detachNewThreadSelector:@selector(runThread:) toTarget:object withObject:nil];

  } else {
    isReachable = NO;
    ncid_network_kill();
  }
}

答案 1 :(得分:0)