我有一个函数,它使用nw_path_monitor_t来注册网络事件。
// Entry point.
// Will be called from AppDelegate when app starts up
void TestNWPathMonitor () {
PrintToFile("TestingNWPathMonitor\n");
NotificationReceiver *notification_receiver = [[NotificationReceiver alloc] init];
// Set up the notification receiver to listen for wifi notification
[notification_receiver RegisterNotification];
monitor = nw_path_monitor_create ();
nw_path_monitor_set_update_handler (monitor, WifiNetworkChangeCB);
nw_path_monitor_start(monitor);
}
我已经提供了回调,当网络事件发生变化时将调用它。在回调中(如下所示),我正在寻找 wifi 事件并将通知发布到默认通知中心。
nw_path_monitor_update_handler_t WifiNetworkChangeCB = ^ (nw_path_t path) {
PrintToFile("Wifi Network change!!\n");
nw_path_status_t status = nw_path_get_status (path);
if (nw_path_uses_interface_type (path, nw_interface_type_wifi)) {
if (status == nw_path_status_satisfied) {
PrintToFile("nw_path_status_satisfied\n");
[[NSNotificationCenter defaultCenter] postNotificationName:@"WifiNetworkChange" object:nil];
} else {
PrintToFile("!(nw_path_status_satisfied)\n");
}
}
};
这是 NotificationReceiver 类:
// NotificationReceiver.h
#include <Foundation/Foundation.h>
@interface NotificationReceiver : NSObject
- (void) HandleNotification : (NSNotification *) pNotification;
- (void) RegisterNotification ;
@end
// NotificaitonReceiver.m
@implementation NotificationReceiver
- (void) HandleNotification : (NSNotification *) pNotification {
PrintToFile([[NSString stringWithFormat:@"Received notification: %@\n", pNotification.name] UTF8String]);
}
- (void) RegisterNotification {
PrintToFile("RegisterNotification!\n");
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(HandleNotification:) name:@"WifiNetworkChange" object:nil];
}
@end
开头调用的 RegisterNotification(如第一个代码片段所示)会将实例添加为观察者,而 HandleNotification 是从 WifiNetworkChangeCB 块发布的 wifi 通知的接收者。
问题是,当我收到 wifi 事件时,会调用WifiNetworkChangeCB 并执行postNotificationName函数(已通过调试器验证),但 HandleNotification 没有收到通知。
我得到以下输出:
TestingNWPathMonitor
RegisterNotification!
Wifi Network change!!
而预期的输出是:
TestingNWPathMonitor
RegisterNotification!
Wifi Network change!!
Received notification: WifiNetworkChange
我已阅读通知中心的文档以了解其用法。也参考了这个答案。我还参考了我正在使用的函数的文档(在解释问题时将它们添加为超链接),一切似乎都很好。
但我显然错过了一些东西(因为它不起作用)。任何帮助将不胜感激。