首页 > 系统 > iOS > 正文

iOS通过Runtime实现友盟统计的实例代码

2020-07-26 02:46:46
字体:
来源:转载
供稿:网友

在友盟官网可以看到相应的步骤,申请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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表