一、技术原理
Method-Swizzling 黑魔法 方法交换(不懂的可以查)某盟页面统计SDK需要开发者在APP基类里实现ViewDidAppear和viewDidDisappear方法,或者在某个特定的类实现以上俩方法,优点是具体情况具体埋点。下面采用无侵入式埋点实现页面统计,无需APP开发者实现以上俩方法,适用于开发开发SDK的公司,无感知采集APP信息。
三、代码实现
#import <UIKit/UIKit.h>
@interface UIViewController (FRHook)
@end
#import "UIViewController+FRHook.h"
#import <objc/runtime.h>
@implementation UIViewController (FRHook)
+(void)load{
Method appearMethod = class_getInstanceMethod([self class], @selector(viewDidAppear:));
Method hookAppearMethod = class_getInstanceMethod([self class], @selector(hook_ViewDidAppear:));
method_exchangeImplementations(appearMethod, hookAppearMethod);
Method disappearMethod = class_getInstanceMethod([self class], @selector(viewDidDisappear:));
Method hookDisappearMethod = class_getInstanceMethod([self class], @selector(hook_viewDidDisappear:));
method_exchangeImplementations(disappearMethod, hookDisappearMethod);
}
- (void)hook_ViewDidAppear:(BOOL)animated
{
[self hook_ViewDidAppear:animated];
if (![self isKindOfClass:[UINavigationController class]]&&![self isKindOfClass:[UITabBarController class]]) {
NSString *appearDetailInfo = [NSString stringWithFormat:@" %@ - %@ - %@", NSStringFromClass([self class]),self.navigationItem.title, @"didAppear"];
// NSLog(@"%@", appearDetailInfo);
//上传到服务器
}
}
- (void)hook_viewDidDisappear:(BOOL)animated
{
[self hook_viewDidDisappear:animated];
if (![self isKindOfClass:[UINavigationController class]]&&![self isKindOfClass:[UITabBarController class]]) {
NSString *disappearDetailInfo = [NSString stringWithFormat:@" %@ - %@ - %@", NSStringFromClass([self class]),self.navigationItem.title, @"didDisappear"];
// NSLog(@"%@", disappearDetailInfo);
//上传到服务器
}
}
四、举一反三
怎么采集用户的的触摸信息?