一种方法是监听来自 Core Foundation Darwin 通知中心的 com.apple.system.config.network_change 事件。
报名参加:
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), //center
NULL, // observer
onNotifyCallback, // callback
CFSTR("com.apple.system.config.network_change"), // event name
NULL, // object
CFNotificationSuspensionBehaviorDeliverImmediately);
这是一个示例回调:
static void onNotifyCallback(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)
{
NSString* notifyName = (NSString*)name;
// this check should really only be necessary if you reuse this one callback method
// for multiple Darwin notification events
if ([notifyName isEqualToString:@"com.apple.system.config.network_change"]) {
// use the Captive Network API to get more information at this point
// https://stackoverflow.com/a/4714842/119114
} else {
NSLog(@"intercepted %@", notifyName);
}
}
例如,请参阅my link to another answer,了解如何使用 Captive Network API 获取当前 SSID。
请注意,虽然我测试的手机已经越狱(iOS 6.1),但我认为这不需要越狱才能正常工作。它当然不需要将应用安装在普通沙盒区域之外 (/var/mobile/Applications/*)。
附:我没有对此进行足够详尽的测试,无法知道此事件是否会产生任何误报(基于您对网络更改的定义)。然而,只要存储一些状态变量就足够简单了,等于最后一个网络的 SSID,并在此事件发生时将其与当前的比较。