在博客开始之前,先说说目前多数开发者使用的几种埋点方案
- 代码复制黏贴到需要统计的类和方法中,工作量大,不利维护
- 使用Method Swizzling机制进行方法替换,将埋点代码统一管理(全局)
- AOP-利用Aspect框架对需要进行统计的方法进行挂钩(hook),并注入包含了统计逻辑的代码块(block)
- 目前本项目中使用的埋点方案
一:使用Method Swizzling机制进行方法替换,将埋点代码统一管理(全局)
使用场景:需要监听全局的某一类的同一方法
这种方案被监听的方法单一,但会影响全局的所有的类的该方法
#import "SXSwizzleTool.h"
#import <objc/runtime.h>
@implementation SXSwizzleTool
+ (void)SXSwizzleWithClass:(Class)processedClass originalSelector:(SEL)originSelector swizzleSelector:(SEL)swizzlSelector
{
Method originalMethod = class_getInstanceMethod(processedClass, originSelector);
Method swizzleMethod = class_getInstanceMethod(processedClass, swizzlSelector);
BOOL didAddMethod = class_addMethod(processedClass, originSelector, method_getImplementation(swizzleMethod), method_getTypeEncoding(swizzleMethod));
if (didAddMethod) {
class_replaceMethod(processedClass, swizzlSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
}else{
method_exchangeImplementations(originalMethod, swizzleMethod);
}
}
@end
在VC分类
中交换viewDidAppear:
和viewDidDisappear:
方法
@implementation UIViewController (SX)
+ (void) load
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
SEL originalAppearSelector = @selector(viewDidAppear:);
SEL swizzleAppearSelector = @selector(swizzleViewDidAppear:);
[SXSwizzleTool sxSwizzleToolWithClass:[self class] originalSelector:originalAppearSelector swizzleSelector:swizzleAppearSelector];
SEL originalDisAppearSelector = @selector(viewDidDisappear:);
SEL swizzleDisAppearSelector = @selector(swizzleViewDidDisappear:);
[SXSwizzleTool sxSwizzleToolWithClass:[self class] originalSelector:originalDisAppearSelector swizzleSelector:swizzleDisAppearSelector];
});
}
- (void) swizzleViewDidAppear:(BOOL)animated
{
[self swizzleViewDidAppear:animated];
if (!self.isNeedMD) {
return;
}
self.mdModel.entry_time = [self getNowTimeString];
// 获取位置信息
[self getLocation];
}
- (void) swizzleViewDidDisappear:(BOOL)animated
{
[self swizzleViewDidDisappear:animated];
if (!self.isNeedMD) {
return;
}
// 上传
[self uploadMDdata];
}
涉及到点击事件时交换sendAction:to:forEvent:
方法
@implementation UIControl (SX)
+ (void) load
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
SEL originSEL = @selector(sendAction:to:forEvent:);
SEL swizzleSEL = @selector(swizzleSendAction:to:forEvent:);
[SXSwizzleTool SXSwizzleWithClass:[self class] originalSelector:originSEL swizzleSelector:swizzleSEL];
});
}
- (void)swizzleSendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event{
[self swizzleSendAction:action to:target forEvent:event];
if (!self.isNeedSwizzle) {
return;
}
NSString *pathString = [[NSBundle mainBundle]pathForResource:@"MaidianVCList" ofType:@"plist"];
NSDictionary *plistDic = [NSDictionary dictionaryWithContentsOfFile:pathString];
// 获取当前SEL string
NSString *selectorName = NSStringFromSelector(action);
// 获取当前类名
NSString *targetName = NSStringFromClass([target class]);
// 获取当前vc 对应的 dic
NSDictionary *controllerDic = plistDic[targetName];
// 之后对此dic做相应的处理
}
Plist根据实际需求配置
当然,同样的效果,你也可直接使用AOP方案来实现
// VC分类中
+ (void)load{
[UIViewController aspect_hookSelector:@selector(viewDidAppear:)
withOptions:AspectPositionAfter
usingBlock:^(id<AspectInfo>aspectInfo){
NSString *className = NSStringFromClass([[aspectInfo instance] class]);;
// 执行埋点操作
} error:nil];
}
// UIControl分类中
+ (void)load{
[UIViewController aspect_hookSelector:@selector(sendAction:to:forEvent:)
withOptions:AspectPositionAfter
usingBlock:^(id<AspectInfo>aspectInfo){
NSString *className = NSStringFromClass([[aspectInfo instance] class]);;
// 执行埋点操作
} error:nil];
}
Aspects
是iOS平台一个轻量级的面向切面编程(AOP)框架,只包括两个方法:一个类方法,一个实例方法
+ (id<AspectToken>)aspect_hookSelector:(SEL)selector
withOptions:(AspectOptions)options
usingBlock:(id)block
error:(NSError **)error;
- (id<AspectToken>)aspect_hookSelector:(SEL)selector
withOptions:(AspectOptions)options
usingBlock:(id)block
error:(NSError **)error;
函数使用方式简单易懂,挂钩的方式为三种:
typedef NS_OPTIONS(NSUInteger, AspectOptions) {
AspectPositionAfter = 0, /// 在原始方法后调用(默认)
AspectPositionInstead = 1, /// 替换原始方法
AspectPositionBefore = 2, /// 在原始方法前调用
AspectOptionAutomaticRemoval = 1 << 3 /// 在执行1次后自动移除
};
调用示例代码:
[UIViewController aspect_hookSelector:@selector(viewWillAppear:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo, BOOL animated) {
//
} error:NULL];
二:在AppDelegate的类方法中根据Plist监听清单进行HOOK
场景需求
:需要监听不同类,不同按钮,系统方法,及表单元点击事件
需要手动创建并管理埋点类的Plist文件
AspectMananer.m
#pragma mark --- 监控button的点击事件
+ (void)trackBttonEvent{
__weak typeof(self) ws = self;
//设置事件统计
//放到异步线程去执行
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//读取配置文件,获取需要统计的事件列表
NSString *path = [[NSBundle mainBundle] pathForResource:@"EventList" ofType:@"plist"];
NSDictionary *eventStatisticsDict = [[NSDictionary alloc] initWithContentsOfFile:path];
for (NSString *classNameString in eventStatisticsDict.allKeys) {
//使用运行时创建类对象
const char * className = [classNameString UTF8String];
//从一个字串返回一个类
Class newClass = objc_getClass(className);
NSArray *pageEventList = [eventStatisticsDict objectForKey:classNameString];
for (NSDictionary *eventDict in pageEventList) {
//事件方法名称
NSString *eventMethodName = eventDict[@"MethodName"];
SEL seletor = NSSelectorFromString(eventMethodName);
NSString *eventId = eventDict[@"EventId"];
[ws trackEventWithClass:newClass selector:seletor eventID:eventId];
[ws trackTableViewEventWithClass:newClass selector:seletor eventID:eventId];
[ws trackParameterEventWithClass:newClass selector:seletor eventID:eventId];
}
}
});
}
#pragma mark -- 1.监控button和tap点击事件(不带参数)
+ (void)trackEventWithClass:(Class)klass selector:(SEL)selector eventID:(NSString*)eventID{
[klass aspect_hookSelector:selector withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo) {
NSString *className = NSStringFromClass([aspectInfo.instance class]);
NSLog(@"className--->%@",className);
NSLog(@"event----->%@",eventID);
if ([eventID isEqualToString:@"xxx"]) {
// [EJServiceUserInfo isLogin]?[MobClick event:eventID]:[MobClick event:@"???"];
}else{
// [MobClick event:eventID];
}
} error:NULL];
}
#pragma mark -- 2.监控button和tap点击事件(带参数)
+ (void)trackParameterEventWithClass:(Class)klass selector:(SEL)selector eventID:(NSString*)eventID{
[klass aspect_hookSelector:selector withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo,UIButton *button) {
NSLog(@"button---->%@",button);
NSString *className = NSStringFromClass([aspectInfo.instance class]);
NSLog(@"className--->%@",className);
NSLog(@"event----->%@",eventID);
} error:NULL];
}
#pragma mark -- 3.监控tableView的点击事件
+ (void)trackTableViewEventWithClass:(Class)klass selector:(SEL)selector eventID:(NSString*)eventID{
[klass aspect_hookSelector:selector withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo,NSSet *touches, UIEvent *event) {
NSString *className = NSStringFromClass([aspectInfo.instance class]);
NSLog(@"className--->%@",className);
NSLog(@"event----->%@",eventID);
NSLog(@"section---->%@",[event valueForKeyPath:@"section"]);
NSLog(@"row---->%@",[event valueForKeyPath:@"row"]);
NSInteger section = [[event valueForKeyPath:@"section"]integerValue];
NSInteger row = [[event valueForKeyPath:@"row"]integerValue];
//统计事件
if (section == 0 && row == 1) {
// [MobClick event:eventID];
}
} error:NULL];
}
Appdelegate.m调用
[AspectMananer trackBttonEvent];
看不明白的来这里 : 运行时Method Swizzling机制与AOP编程
事实上上述方案是直接从上述链接中复制过来的,因为通俗易懂,就没做自己的处理
三. 项目使用方案
作为贷款类app,我们对申请借款的几个流程界面进行了埋点处理,但现行的埋点方案并没做到完全解耦,有更好的方案可私信我
,在此谢过!
我们的需求是每一个页面都要进行定位并获取用户的部分信息(包含进出页面时间、手机型号、网络ip、当前页面部分数据等)上传服务端
分类VC.h
#import <UIKit/UIKit.h>
#import "SXNavigationController.h"
#import <CoreLocation/CoreLocation.h>
#import "SXMDModel.h"
@interface UIViewController (SX)<CLLocationManagerDelegate>
/* 自定义导航控制器相关 */
@property (nonatomic, assign) BOOL enablePopGestureRecognizer;
@property (nonatomic, strong) SXNavigationController *sx_navigationController;
/* 埋点相关 */
@property (nonatomic, assign) BOOL isNeedMD;//是否需要埋点
@property (nonatomic, strong) SXMDModel *mdModel;//埋点model
@property (nonatomic, strong) CLLocationManager *locationmanager;
/*
* requestId @param 订单id
* pageTag @param 类似于EventID
* isNeedMD @param 当前页面是否需要埋点
*/
- (void) transferRequestId:(NSString *)requestId pageTag:(NSString *)pageTag isNeedMD:(BOOL)isNeedMD;
@end
分类VC.m
#import "UIViewController+SX.h"
#import <objc/runtime.h>
#import "SXSwizzleTool.h"
#import "SXPersonalParam.h"
#import "SXUserModel.h"
#import "SXLogTool.h"
#import "SXCommonTool.h"
static char const * const ISNEEDMD = "isNeedMD";
@implementation UIViewController (SX)
- (BOOL)enablePopGestureRecognizer {
return [objc_getAssociatedObject(self, _cmd) boolValue];
}
- (void)setEnablePopGestureRecognizer:(BOOL)enablePopGestureRecognizer {
objc_setAssociatedObject(self, @selector(enablePopGestureRecognizer), @(enablePopGestureRecognizer), OBJC_ASSOCIATION_RETAIN);
}
- (SXNavigationController *)sx_navigationController {
return objc_getAssociatedObject(self, _cmd);
}
- (void)setSx_navigationController:(SXNavigationController *)sx_navigationController {
objc_setAssociatedObject(self, @selector(sx_navigationController), sx_navigationController, OBJC_ASSOCIATION_RETAIN);
}
/***********************埋点相关*************************/
- (BOOL) isNeedMD
{
NSNumber *number = objc_getAssociatedObject(self, ISNEEDMD);
return [number boolValue];
}
- (void) setIsNeedMD:(BOOL)isNeedMD
{
NSNumber *number = [NSNumber numberWithBool:isNeedMD];
objc_setAssociatedObject(self, ISNEEDMD, number, OBJC_ASSOCIATION_RETAIN);
}
- (SXMDModel *) mdModel
{
return objc_getAssociatedObject(self, _cmd);
}
- (void) setMdModel:(SXMDModel *)mdModel
{
objc_setAssociatedObject(self, @selector(mdModel), mdModel, OBJC_ASSOCIATION_RETAIN);
}
- (CLLocationManager *) locationmanager
{
return objc_getAssociatedObject(self, _cmd);
}
- (void) setLocationmanager:(CLLocationManager *)locationmanager
{
objc_setAssociatedObject(self, @selector(locationmanager), locationmanager, OBJC_ASSOCIATION_RETAIN);
}
+ (void) load
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
SEL originalAppearSelector = @selector(viewDidAppear:);
SEL swizzleAppearSelector = @selector(swizzleViewDidAppear:);
[SXSwizzleTool sxSwizzleToolWithClass:[self class] originalSelector:originalAppearSelector swizzleSelector:swizzleAppearSelector];
SEL originalDisAppearSelector = @selector(viewDidDisappear:);
SEL swizzleDisAppearSelector = @selector(swizzleViewDidDisappear:);
[SXSwizzleTool sxSwizzleToolWithClass:[self class] originalSelector:originalDisAppearSelector swizzleSelector:swizzleDisAppearSelector];
});
}
- (void) swizzleViewDidAppear:(BOOL)animated
{
[self swizzleViewDidAppear:animated];
if (!self.isNeedMD) {
return;
}
self.mdModel.entry_time = [self getNowTimeString];
// 获取位置信息
[self getLocation];
}
- (void) swizzleViewDidDisappear:(BOOL)animated
{
[self swizzleViewDidDisappear:animated];
if (!self.isNeedMD) {
return;
}
// 上传(这里本人提出过数据存储,按时间段或者数据条数上传,未被采纳,说是后期再作考虑,然而......)
[self uploadMDdata];
}
-(void)getLocation
{
//判断定位功能是否打开
if ([CLLocationManager locationServicesEnabled]) {
self.locationmanager = [[CLLocationManager alloc]init];
self.locationmanager.delegate = self;
[self.locationmanager requestWhenInUseAuthorization];
//设置寻址精度
self.locationmanager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationmanager.distanceFilter = 5.0;
[self.locationmanager startUpdatingLocation];
}
}
#pragma mark CoreLocation delegate (定位失败)
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
self.mdModel.latitude = @"";
self.mdModel.longitude = @"";
}
#pragma mark 定位成功后则执行此代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
[self.locationmanager stopUpdatingHeading];
CLLocation *currentLocation = [locations lastObject];
self.mdModel.latitude = [NSString stringWithFormat:@"%.5f",currentLocation.coordinate.latitude];
self.mdModel.longitude = [NSString stringWithFormat:@"%.5f",currentLocation.coordinate.longitude];
}
#pragma mark - 上传埋点信息
- (void) uploadMDdata
{
self.mdModel.submit_time = [self getNowTimeString];
/* 添加埋点 */
SXUserModel *model = [SXLogTool getLoginUser];
CafintechSecurityForiOS *cafintechSecurity = [[CafintechSecurityForiOS alloc] init];
NSString *deviceJson = [cafintechSecurity getPhoneInfoWithJsonStringLongitude:self.mdModel.longitude Latitude:self.mdModel.latitude];
NSDictionary *deviceDic = [deviceJson jsonStringToDictionary];
[deviceDic setValue:model.mobile forKey:@"mobile"];
[deviceDic setValue:model.token forKey:@"token"];
[deviceDic setValue:self.mdModel.requestId forKey:@"requestId"];
[deviceDic setValue:self.mdModel.page_tag forKey:@"page_tag"];
[deviceDic setValue:self.mdModel.entry_time forKey:@"entry_time"];
[deviceDic setValue:self.mdModel.submit_time forKey:@"submit_time"];
SXPersonalParam *param = [SXPersonalParam personalParamWithData:deviceDic serviceId:@"JUNCAI0055"];
[SXCommonTool commonToolWithParam:param success:^(SXCommonResult *result) {
} failure:^(NSError *error) {
}];
}
- (void) transferRequestId:(NSString *)requestId pageTag:(NSString *)pageTag isNeedMD:(BOOL)isNeedMD
{
self.mdModel = [[SXMDModel alloc]init];
self.isNeedMD = isNeedMD;//也可嵌入mdModel
self.mdModel.requestId = requestId;
self.mdModel.page_tag = pageTag;
}
- (NSString *) getNowTimeString
{
NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
return [formatter stringFromDate:date];
}
@end
之所以说未完全从页面中分离出来,是因为需要在当前需要埋点的vc中做以下配置
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// requestId:订单号 pagTag:页面标志 isNeedMD:是否需要埋点
[self transferRequestId:self.caseNumModel.requestId pageTag:@"2" isNeedMD:YES];
}
事实上从技术上是可以做到完全解耦,就是为每个页面生成一个model用于存储requestId、pageTag、isNeedMD等信息,在分类中取出即可,但是这样并没有比现有方案简单,所以暂不采纳!
运行时Method Swizzling机制与AOP编程
可复用而且高度解耦的用户统计埋点实现
关于埋点的思考
无侵入埋点
最后,有任何疑问或者建议,欢迎敲门骚扰!
网友评论