在友盟官網可以看到相應的步驟,申請appkey,導入SDK,然後在AppDelegate裡面寫入相應的代碼,下面就是關鍵的代碼:
實現頁面的統計需要在每個UIViewController中配對調用如下方法:
- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [MobClick beginLogPageView:@"PageOne"];//("PageOne"為頁面名稱,可自定義) } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [MobClick endLogPageView:@"PageOne"]; }
幾年之前做過這個,那時候才剛開始做iOS,就按照這個文檔在每一個UIViewController裡面寫了這個方法,現在看來真是太low了。
這次又做這個友盟統計,就想起來用runtime解決這個問題。
在工程中創建一個UIViewController的Category,然後通過Runtime動態添加兩個方法,分別替代viewWillAppear和viewWillDisappear方法。這樣就不需要在每一個 UIViewController寫這段代碼了。
新建一個分類:
UIViewController+Statistics.h
// // UIViewController+Statistics.h // TongYuanHospital // // Created by ZSP on 2017/6/16. // Copyright © 2017年 ZSP. All rights reserved. // #import <UIKit/UIKit.h> @interface UIViewController (Statistics) @end
UIViewController+Statistics.m
// // UIViewController+Statistics.m // TongYuanHospital // // Created by ZSP on 2017/6/16. // Copyright © 2017年 ZSP. All rights reserved. // #import "UIViewController+Statistics.h" @implementation UIViewController (Statistics) + (void)load { //原本的viewWillApper方法 Method viewWillAppear = class_getInstanceMethod(self, @selector(viewWillAppear:)); //需要替換成能夠輸入日志的viewWillAppear Method logViewWillAppear = class_getInstanceMethod(self, @selector(logViewWillAppear:)); //原本的viewWillDisappear方法 Method viewWillDisappear = class_getInstanceMethod(self, @selector(viewWillDisappear:)); //需要替換成能夠輸入日志的viewWillDisappear Method logviewWillDisappear = class_getInstanceMethod(self, @selector(logviewWillDisappear:)); //兩方法進行交換 method_exchangeImplementations(viewWillAppear, logViewWillAppear); method_exchangeImplementations(viewWillDisappear, logviewWillDisappear); } -(void)logViewWillAppear:(BOOL)animated { [self logViewWillAppear:animated]; NSString *selfClass = NSStringFromClass([self class]); [MobClick beginLogPageView:selfClass]; //當然這裡也可以使用self.title作為頁面的名稱,這樣在友盟後台查看的時候更加方便些 //[MobClick endLogPageView:self.title]; } -(void)logviewWillDisappear:(BOOL)animated { [self logviewWillDisappear:animated]; NSString *selfClass = NSStringFromClass([self class]); [MobClick endLogPageView:selfClass]; } @end
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。