因为这篇文章主要分析Mixpanel中可视化ABTest部分,所以代码中会忽略其他部分代码,其他代码部分会用"…"表示,且文章描述中仅针对ABTest部分。
1. 添加手势开启websocket
Mixpanel的初始化函数比较多,主要的初始化函数为下面这个。该函数初始化了websocket的url,并添加了开启websocket的手势。
- (instancetype)initWithToken:(NSString *)apiToken
launchOptions:(NSDictionary *)launchOptions
flushInterval:(NSUInteger)flushInterval
trackCrashes:(BOOL)trackCrashes
automaticPushTracking:(BOOL)automaticPushTracking
optOutTrackingByDefault:(BOOL)optOutTrackingByDefault
{
......
// switchboardURL为websocket连接的url地址
self.switchboardURL = @"wss://switchboard.mixpanel.com";
......
// Mixpanel通过版本控制了是否支持可视化ABTest,v3.0.1之后的版本均支持,在后续代码中会看到关于enableVisualABTestAndCodeless的判断
#if defined(DISABLE_MIXPANEL_AB_DESIGNER) // Deprecated in v3.0.1
self.enableVisualABTestAndCodeless = NO;
#else
self.enableVisualABTestAndCodeless = YES;
#endif
......
// setUpListeners会设置手势用于启动websocket服务
[self setUpListeners];
......
}
- (void)setUpListeners
{
......
[self initializeGestureRecognizer];
}
/**
* 通过UILongPressGestureRecognizer手势开启websocket服务
*/
- (void)initializeGestureRecognizer
{
#if !MIXPANEL_NO_NOTIFICATION_AB_TEST_SUPPORT
if (![Mixpanel isAppExtension]) {
dispatch_async(dispatch_get_main_queue(), ^{
self.testDesignerGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self
action:@selector(connectGestureRecognized:)];
self.testDesignerGestureRecognizer.minimumPressDuration = 3;
self.testDesignerGestureRecognizer.cancelsTouchesInView = NO;
#if TARGET_IPHONE_SIMULATOR
self.testDesignerGestureRecognizer.numberOfTouchesRequired = 2;
#else
self.testDesignerGestureRecognizer.numberOfTouchesRequired = 4;
#endif
// because this is in a dispatch_async, if the user sets enableVisualABTestAndCodeless in the first run
// loop then this is initialized after that is set so we have to check here
self.testDesignerGestureRecognizer.enabled = self.enableVisualABTestAndCodeless;
[[Mixpanel sharedUIApplication].keyWindow addGestureRecognizer:self.testDesignerGestureRecognizer];
});
}
#endif // MIXPANEL_NO_NOTIFICATION_AB_TEST_SUPPORT
}
其中[Mixpanel sharedUIApplication]函数用于获取UIApplicaiton:
+ (UIApplication *)sharedUIApplication
{
if ([[UIApplication class] respondsToSelector:@selector(sharedApplication)]) {
return [[UIApplication class] performSelector:@selector(sharedApplication)];