iOS通过Runtime实现友盟统计的实例代码
程序员文章站
2023-12-19 13:50:04
在友盟官网可以看到相应的步骤,申请appkey,导入sdk,然后在appdelegate里面写入相应的代码,下面就是关键的代码:
实现页面的统计需要在每个uiviewco...
在友盟官网可以看到相应的步骤,申请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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。