前言
埋点统计在产品运营过程中对用户行为分析、产品前期的业务模式探索起着很重要的作用。常用的三种埋点方式主要包括手动埋点、可视化埋点和无痕埋点。
手动埋点主要是通过手写代码的方式哪里需要埋哪里,优点是数据精准、方便调试、能够自定义所需的变量值,缺点是工作量较大、埋点代码多容易产生冗余、后期难维护等;
可视化埋点指前端或者APP端基于DOM元素和控件所精准自动埋点的上报的方案,优点是相比较于无埋点相而言对较低,但是这个可视化元素的识别技术是客户端或者前端所要实现的,唯一 ID 生成也无需客户端去自定义规则,这套生成规则由相关产品在自动化工具的情况下生成配置表,下发到客户端,再由客户端按坑就班到相关界面去实现、数据量相对精确。缺点是可视化工具的平台的搭建,静态页面的元素识别都需要额外开发、动态效果可能会遗漏。(可参考:可视化埋点(2):iOS端实现)
无痕埋点指的是通过编译工具、预编译替换代码等,直接由SDK全部负责采集上报,优点是代码不会出现在业务代码中、容易管理和维护,缺点是后期的结息比较复杂、view_path不能做到100%唯一、后端或产品人员数据分析工作量大。
三种埋点方案中,可视化埋点和无痕埋点,都属于无侵入的埋点方案,因为它们都不需要在业务代码中写入埋点代码。采用无侵入埋点方案,既可以做到埋点被统一维护,又可以实现和工程代码的解耦。其中无痕埋点方案能够满足大多数应用的埋点需求。
无痕埋点方案介绍
最常见的三种埋点类型有页面进入次数、页面停留时间、点击事件。对于这三种常见的情况,我们都可以通过runtime
的method swizzling
来插入埋点代码,以实现无侵入的埋点方法,可分三步来处理:实现替换、生成唯一标识、数据上报。
新建一个方法替换类NSObject+Logger,加上替换的方法swizzleSelectorFromSelector : toSelector :
,代码如下:
+ (void)swizzleSelectorFromSelector:(SEL)originalSelector toSelector:(SEL)swizzledSelector {
Method originalMethod = class_getInstanceMethod(self, originalSelector);
Method swizzledMethod = class_getInstanceMethod(self, swizzledSelector);
BOOL didAddMethod =
class_addMethod(self,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(self,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
这个方法利用运行时method_exchangeImplementations
接口将方法的实现进行了交换,原方法调用时就会被hook住,从而去执行指定的方法。
页面进入次数、页面停留时间事件
页面进入次数、页面停留时间需要对UIViewController
生命周期进行埋点,可以创建一个UIViewController
的Category
,通过NSObject+Logger
将原生方法替换,代码如下:
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = NSClassFromString(@"UIViewController");
[class swizzleSelectorFromSelector:@selector(viewWillAppear:) toSelector:@selector(hook_viewWillAppear:)];
[class swizzleSelectorFromSelector:@selector(viewWillDisappear:) toSelector:@selector(hook_viewWillDisappear:)];
});
}
- (void)hook_viewWillAppear:(BOOL)animated {
//先执行插入代码,再执行原 viewWillAppear 方法
[self insertToViewWillAppear];
[self hook_viewWillAppear:animated];
}
- (void)hook_viewWillDisappear:(BOOL)animated {
//先执行插入代码,再执行原 viewWillDisappear 方法
[self insertToViewWillDisappear];
[self hook_viewWillDisappear:animated];
}
数据上报部分这里没有做具体介绍,可以自行对接自己的后端接口或者一些第三方平台,如友盟。
## 点击事件
常用的控件如UIButton、UITextField、UISwitch、UISegmentedControl、UISlider 等,它们的父类都是UIControl ,我们可对sendAction:to:forEvent: 进行拦截,代码如下:
+ (void) load { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ //可监听到UIButton、UITextField、UISwitch、UISegmentedControl、UISlider 、UIStepper等控件的Action事件 [self swizzleSelectorFromSelector:@selector(sendAction:to:forEvent:) toSelector:@selector(hook_sendAction:to:forEvent:)]; }); } #pragma mark-- #pragma 按钮点击 - (void)hook_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event { [self insertToSendAction:action to:target forEvent:event]; [self hook_sendAction:action to:target forEvent:event]; } - (void)insertToSendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event { //日志记录 if ([[[event allTouches] anyObject] phase] == UITouchPhaseEnded) { NSString *actionString = NSStringFromSelector(action); NSString *targetString = NSStringFromClass([target class]); NSLog(@"唯一标识:%@_%@_%@", targetString, self.accessibilityIdentifier, actionString); } }
唯一标识
这里的唯一标识组成规则是NSStringFromClass([target class])+self.accessibilityIdentifier
,accessibilityIdentifier+NSStringFromSelector(action)
,accessibilityIdentifier
系统默认为nil
,我们需要根据不同控件的特性为accessibilityIdentifier
进行赋值,如UIButton
控件的accessibilityIdentifier
可以是控件的变量名,考虑到用XIB
或SB
布局不一定会定义变量,可取button
的title
值或者image
的名字来定义,新建一个UIView+Logger
类:
@implementation UIView (Logger)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = NSClassFromString(@"UIView");
[class swizzleSelectorFromSelector:@selector(accessibilityIdentifier) toSelector:@selector(hook_accessibilityIdentifier)];
});
}
#pragma mark - Method Swizzling
- (NSString *)hook_accessibilityIdentifier {
NSString *labelStr = [self.superview findNameWithInstance:self];
if (labelStr && ![labelStr isEqualToString:@""]) {
//SB或XIB布局的,因获取不到image的name,所以至少要拉个变量名
labelStr = [NSString stringWithFormat:@"%@",labelStr];
} else {
if ([self isKindOfClass:[UIButton class]]) {
//UIButton 使用 button 的 text 和 image
labelStr = [NSString stringWithFormat:@"%@%@",((UIButton *)self).titleLabel.text?:@"",((UIButton *)self).imageView.image.accessibilityIdentifier?:@""];
}
}
[self setAccessibilityIdentifier:labelStr];
return labelStr;
}
@end
findNameWithInstance:
的实现
- (NSString *)findNameWithInstance:(UIView *)instance
{
id nextResponder = [self nextResponder];
NSString *name = [RuntimeHelper nameWithClass:self instance:instance];
if (!name) {
return [nextResponder findNameWithInstance:instance];
}
if ([name hasPrefix:@"_"]) { //去掉变量名的下划线前缀
name = [name substringFromIndex:1];
}
return name;
}
这里又延伸出了一个问题,UIImage
并没有提供获取资源名字的方法。解决问题的方式是通过替换 UIImage
的 imageNamed:
方法对 UIImage
的accessibilityIdentifier
进行赋值:
@implementation UIImage (Logger)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class imageClass = NSClassFromString(@"UIImage");
[object_getClass(imageClass) swizzleSelectorFromSelector:@selector(imageNamed:) toSelector:@selector(hook_imageNamed:)];
});
}
+ (UIImage *)hook_imageNamed:(NSString *)imageName {
UIImage *image = [UIImage hook_imageNamed:imageName];
image.accessibilityIdentifier = imageName;
return image;
}
Delegate事件
Delegate
事件的 swizzling
需要分成两步,第一步先替换掉 setDelegate:
,其次是对 Delegate
事件的替换,举个 UIScrollView
的例子:
//我们要保证在每个控制器里都执行一次,所以替换的方法都会加上class name的前缀,以示区别
#define GET_CLASS_CUSTOM_SEL(sel,class) NSSelectorFromString([NSString stringWithFormat:@"%@_%@",NSStringFromClass(class),NSStringFromSelector(sel)])
@implementation UIScrollView (Logger)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[[self class] swizzleSelectorFromSelector:@selector(setDelegate:) toSelector:@selector(hook_setDelegate:)];
});
}
- (void)hook_setDelegate:(id)delegate {
// 由于setDelegate方法可能被多次调用,所以要判断是否已经swizzling了,防止重复执行。
if (![[self class] delegate:delegate isContain:@selector(scrollViewWillBeginDragging:)]) {
[self hook_scrollViewWillBeginDragging:delegate];
}
if ([NSStringFromClass([self class]) isEqualToString:@"UITableView"]){
if (![[self class] delegate:delegate isContain:@selector(tableView:didSelectRowAtIndexPath:)]) {
[(UITableView *)self hook_tableViewDidSelectRowAtIndexPathInClass:delegate];
}
}
[self hook_setDelegate:delegate];
}
#pragma --
#pragma UIScrollViewDelegate
- (void)hook_scrollViewWillBeginDragging:(id)delegate {
[[self class] swizzleDelegate:delegate originSelector:@selector(scrollViewWillBeginDragging:) swizzleSelector:@selector(insertToScrollViewWillBeginDragging:)];
}
- (void)insertToScrollViewWillBeginDragging:(UIScrollView *)scrollView {
SEL sel = GET_CLASS_CUSTOM_SEL(@selector(scrollViewWillBeginDragging:),[self class]);
if ([self respondsToSelector:sel]) {
IMP imp = [self methodForSelector:sel];
void (*func)(id, SEL,id) = (void *)imp;
NSLog(@"标识:%@_%@_%@", NSStringFromClass([self class]), [RuntimeHelper nameWithClass:self instance:scrollView], NSStringFromSelector(@selector(scrollViewWillBeginDragging:)));
func(self, sel, scrollView);
}
}
NSObject+Logger
类新增 delegate: isContain:
和 swizzleDelegate: originSelector: swizzleSelector:
两个方法,完整代码如下:
#define GET_CLASS_CUSTOM_SEL(sel,class) NSSelectorFromString([NSString stringWithFormat:@"%@_%@",NSStringFromClass(class),NSStringFromSelector(sel)])
@implementation NSObject (Logger)
+ (void)swizzleSelectorFromSelector:(SEL)originalSelector toSelector:(SEL)swizzledSelector {
Method originalMethod = class_getInstanceMethod(self, originalSelector);
Method swizzledMethod = class_getInstanceMethod(self, swizzledSelector);
// NSLog(@"__delegateObject %@", [self class]);
BOOL didAddMethod =
class_addMethod(self,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(self,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
+ (BOOL)delegate:(id)delegateObject isContain:(SEL)selector {
return [self isContainSel:GET_CLASS_CUSTOM_SEL(selector, [delegateObject class]) inClass:[delegateObject class]];
}
+ (void)swizzleDelegate:(id)delegateObject originSelector:(SEL)originSelector swizzleSelector:(SEL)swizzleSelector {
SEL newSelector = GET_CLASS_CUSTOM_SEL(originSelector, [delegateObject class]);
Method swizzledMethod = class_getInstanceMethod([delegateObject class], swizzleSelector);
//增加swizzle delegate method
class_addMethod([delegateObject class],
newSelector,
method_getImplementation(class_getInstanceMethod([self class], swizzleSelector)),
method_getTypeEncoding(swizzledMethod));
Method swizzleDelegateMethod = class_getInstanceMethod([delegateObject class], newSelector);
Method originDelegateMethod = class_getInstanceMethod([delegateObject class], originSelector);
// 将swizzle delegate method 和 origin delegate method 交换
method_exchangeImplementations(swizzleDelegateMethod, originDelegateMethod);
}
+ (BOOL)isContainSel:(SEL)sel inClass:(Class)class {
unsigned int count;
Method *methodList = class_copyMethodList(class,&count);
for (int i = 0; i < count; i++) {
Method method = methodList[i];
NSString *tempMethodString = [NSString stringWithUTF8String:sel_getName(method_getName(method))];
if ([tempMethodString isEqualToString:NSStringFromSelector(sel)]) {
return YES;
}
}
return NO;
}
数据上报的方式这里没有做过多的介绍,可通过集成第三方统计平台或自搭服务进行对接,完整的DEMO参考这里。
参考文献:
可视化埋点(1):思路
iOS无埋点数据统计实践