在友盟官网可以看到相应的步骤,申请appkey,导入SDK,然后在AppDelegate里面写入相应的代码,下面就是关键的代码:
实现页面的统计需要在每个UIViewController中配对调用如下方法:
1
2
3
4
5
6
7
8
9
10
|
- ( 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
1
2
3
4
5
6
7
8
9
10
11
12
13
|
//
// 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
//
// 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
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.jianshu.com/p/3bc36c5eb82e?utm_source=tuicool&utm_medium=referral