使用Method Swizzling為UIViewController加入自動(dòng)統(tǒng)計(jì)功能

在使用友盟,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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容