测量事件:以 NSNotification
作为跟踪事件
发布测量事件。
[AQSEvent postEvent:@"event_name" args:@{
@"key": @"value"
}];
观察测量事件。
self.observer = [AQSEvent observeWithBlock:^(NSString *eventName, NSDictionary *eventArgs) {
// Do something with arguments.
//
// Typically perform actual tracking events in this block.
}];
测量事件是一个符合以下协议的 NSNotification
。
userInfo
,其中包含以下值NSString
。NSDictionary
。在方法中测试 [Analytics trackSomething]
的调用几乎是不可行的。
以初始化参数作为分析实例?无稽之谈。
iOS 发布了大量的 NSNotification
,通知应用生命周期事件和 iCloud 事件等...
第三方库也是如此。
然而,有许多 NSNotification
名称和 userInfo
格式。为了跟踪事件,我们必须找到哪些 NSNotification
,编写许多 NSNotification
监听器,并对每个格式的 userInfo
进行解析和重新格式化。
NSNotification
的 - 这意味着您可以使用 Expecta
的 notify()
测试它kAQSEvent
的 NSNotification
。只有一个观察者。您只需将参数发送到您的分析跟踪代码。(因为大多数分析提供使用名称和字典参数跟踪事件。)这只是 NSNotification
。没有魔法般的事情。容易理解。
AQSEvent
提供了一个发布/订阅事件的辅助工具。
[AQSEvent postEvent:@"location/changed" args:@{
@"latitude": @(40.712784),
@"longitude": @(-74.005941)
}];
这是以下代码的简写。
[[NSNotificationCenter defaultCenter] postNotification:kAQSEvent object:nil userInfo:@{
kAQSEventName: @"location/changed",
kAQSEventArgs: @{
@"latitude": @(40.712784),
@"longitude": @(-74.005941)
};
}];
订阅事件也很简单。
AQSEvent
提供了一个辅助工具。
@property (nonatomic, strong) AQSEventObserver *eventObserver;
// Then in @implementation,
self.eventObserver = [AQSEvent observeWithBlock:^(NSString *eventName, NSDictionary *eventArgs) {
// Do something
}];
这是以下代码的简写。
[[NSNotificationCenter defaultCenter] addObserver:kAQSEvent selector:@selector(subscribeEvent:) object:nil];
AQSEventObserver
在 - dealloc
的时候会自动执行 - removeObserver:
。只要您使用 AQSEvent
来监听事件,就不会出现内存泄漏。
假设您想测试以下方法是否发布了一个用于跟踪的事件。
[someObject doSomething];
帮助您测试测量事件。而
AQSEvent
为简化测试提供了辅助类别。
- (void)testItPostsSomeMeasurementEvent {
XCTestExpectation *expectation = [self expectationForNotification:kAQSEvent object:nil handler:BOOL^(NSNotification *notification) {
[expectation fulfill];
return [notification aqs_isEqualToMeasurementEvent:@"event_name" args:@{@"key": @"value"}];
}];
[someObject doSomething]; // Assume it posts "event_name" event with {"key": "value"}
[self waitForExpectationWithTimeout:1.0 handler:nil];
}
pod "AQSEvent"