AQSEvent 0.2.0

AQSEvent 0.2.0

测试已测试
Lang语言 Obj-CObjective C
许可证 MIT
Released最新发布2014年12月

kaiinui 维护。



AQSEvent 0.2.0

  • kaiinui

测量事件:以 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

  1. 事件 的通知名称应该始终相同。
  2. 事件 的通知应包含一个 userInfo,其中包含以下值
    1. userInfo 应包含事件名称作为 NSString
    2. userInfo 应包含事件参数作为 NSDictionary

优势?

测试方法调用通常是困难的

在方法中测试 [Analytics trackSomething] 的调用几乎是不可行的。

以初始化参数作为分析实例?无稽之谈。

没有统一的格式发布事件的方法被普遍接受

iOS 发布了大量的 NSNotification,通知应用生命周期事件和 iCloud 事件等...

第三方库也是如此。

然而,有许多 NSNotification 名称和 userInfo 格式。为了跟踪事件,我们必须找到哪些 NSNotification,编写许多 NSNotification 监听器,并对每个格式的 userInfo 进行解析和重新格式化。

测量事件可能是圣杯

  1. 它是基于 NSNotification 的 - 这意味着您可以使用 Expectanotify() 测试它
  2. 您只需要跟踪名称为 kAQSEventNSNotification。只有一个观察者。您只需将参数发送到您的分析跟踪代码。(因为大多数分析提供使用名称和字典参数跟踪事件。)

这只是 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"

相关项目