在使用友盟,LeanCloud,Flurry这些第三方统计服务的时候,我们经常要在UIViewController里写这样的代码:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[MobClick beginLogPageView:@"公司信息"];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[MobClick endLogPageView:@"公司信息"];
}
Method Swizzling 是一个 基于 Objective-C的 一个小技巧,可以在运行时修改类的实现。
基于Method Swizzling,我们就可以修改UIViewController中viewWillAppear:和viewWillDisappear:的实现,自动加入统计代码。
下面是之前的一段很早以前的学习的时候写的代码,抛砖引玉。这是把当前的ViewController的名字作为页面名称统计的,实际上可以先获取下有没有一个返回页面名称的方法,或者NSString的property,没有的话再使用默认的 ViewController类名。这样方便配置页面名称,又可以精简代码。
#import "UIViewController+AutoLog.h"
@implementation UIViewController (AutoLog)
-(void)printSender: (id)sender{
NSLog(@"sender : => %@", NSStringFromClass([sender class]));
}
-(void)autolog_viewWillAppear: (BOOL) animated{
NSLog(@"apper");
NSLog(@"%@", NSStringFromClass([self class]));
[AVAnalytics beginLogPageView:NSStringFromClass([self class])];
[self autolog_viewWillAppear:animated];
}
-(void)autolog_viewWillDisAppear: (BOOL) animated{
NSLog(@"disapper");
[self autolog_viewWillAppear:animated];
[AVAnalytics endLogPageView:NSStringFromClass([self class])];
}
@end
#import "AppDelegate.h"
#import <OneAPM/OneAPM.h>
#import <objc/runtime.h>
#import "UIViewController+AutoLog.h"
@implementation AppDelegate
void Swizzle(Class c, SEL orig, SEL new) {
Method origMethod = class_getInstanceMethod(c, orig);
Method newMethod = class_getInstanceMethod(c, new);
if(class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)))
class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
else
method_exchangeImplementations(origMethod, newMethod);
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
Swizzle([UIViewController class], @selector(viewWillAppear:), @selector(autolog_viewWillAppear:));
Swizzle([UIViewController class], @selector(viewWillDisappear:), @selector(autolog_viewWillDisAppear:));
[AVOSCloud setApplicationId:@"your id"
clientKey:@"your key"];
[AVAnalytics trackAppOpenedWithLaunchOptions:launchOptions];
return YES;
}
实际使用Method Swizzling建议使用 https://github.com/rentzsch/jrswizzle