在使用友盟,LeanCloud,F(xiàn)lurry這些第三方統(tǒng)計(jì)服務(wù)的時(shí)候,我們經(jīng)常要在UIViewController里寫這樣的代碼:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[MobClick beginLogPageView:@"公司信息"];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[MobClick endLogPageView:@"公司信息"];
}
Method Swizzling 是一個(gè) 基于 Objective-C的 一個(gè)小技巧,可以在運(yùn)行時(shí)修改類的實(shí)現(xiàn)。
基于Method Swizzling,我們就可以修改UIViewController中viewWillAppear:和viewWillDisappear:的實(shí)現(xiàn),自動(dòng)加入統(tǒng)計(jì)代碼。
下面是之前的一段很早以前的學(xué)習(xí)的時(shí)候?qū)懙拇a,拋磚引玉。這是把當(dāng)前的ViewController的名字作為頁面名稱統(tǒng)計(jì)的,實(shí)際上可以先獲取下有沒有一個(gè)返回頁面名稱的方法,或者NSString的property,沒有的話再使用默認(rèn)的 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;
}
實(shí)際使用Method Swizzling建議使用 https://github.com/rentzsch/jrswizzle