iOS 下的AOP编程之打点统计

作者: _冷忆 | 来源:发表于2017-07-31 16:32 被阅读71次

    概念

    AOP编程也叫面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续是函数式编程的一种衍生范型。主要作用对业务逻辑的各个部分进行隔离,解耦。就是一种解耦的思想。

    典型业务范围

    • 日志记录
    • 性能统计
    • 用户行为数据统计
    • 权限控制

    iOS下的实现

    网上关于这方面的例子很多,都是云里雾里,你就觉得很牛逼,然后就总觉得少了什么,不得要领,看到这博文的你,算有福了,本教程举个简单的日志记录系统,演示AOP的工作流程,废话不说上码。

    建立工程项目命名 AOP ViewController代码如下
    ViewController.h

    @interface ViewController : UIViewController
    @end
    

    ViewController.m

    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    }
    
    - (void)viewDidAppear:(BOOL)animated{
        
    }
    
    @end
    

    只有一个按钮点击事件,其它啥也没有。

    再建一个统计类 Stastic
    Stastic.h

    #import <Foundation/Foundation.h>
    
    @interface Stastic : NSObject
    
    + (void)stasticWithEventName:(NSString *)eventName;
    
    @end
    

    Stastic.m

    #import "Stastic.h"
    
    @implementation Stastic
    + (void)stasticWithEventName:(NSString *)eventName{
        NSLog(@"-----> %@",eventName);
    }
    @end
    

    开始事件的统计,一般做法都是如下,表示用户浏览了ViewController页面

    - (void)viewDidAppear:(BOOL)animated{
        [Stastic stasticWithEventName:@"ViewController"];
    }
    

    AOP做法

    建立ViewController类别

    UIViewController+Stastic.h

    #import <UIKit/UIKit.h>
    
    @interface UIViewController (Stastic)
    
    @end
    

    UIViewController+Stastic.m

    #import "UIViewController+Stastic.h"
    #import "Stastic.h"
    #import <objc/runtime.h>
    #import <objc/objc.h>
    
    @implementation UIViewController (Stastic)
    + (void)load{
        swizzleMethod([self class], @selector(viewDidAppear:), @selector(swizzled_viewDidAppear:));
    }
    
    - (void)swizzled_viewDidAppear:(BOOL)animated{
        // call original implementation
        [self swizzled_viewDidAppear:animated];
        // Begin Stastic Event
        [Stastic stasticWithEventName:@"UIViewController"];
    }
    
    void swizzleMethod(Class class,SEL originalSelector,SEL swizzledSelector){
        // the method might not exist in the class, but in its superclass
        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
        
        // class_addMethod will fail if original method already exists
        BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
        
        // the method doesn’t exist and we just added one
        if (didAddMethod) {
            class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
        }
        else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    }
    
    @end
    
    
    1. swizzled_viewDidAppear:(BOOL)animated 里面又调用了自己看起来像递归,实际上因为tuntime的作用函数实现已经被交换了。调用 viewDidAppear: 会调用你实现的 swizzled_viewDidAppear:,而在 swizzled_viewDidAppear: 里调用 swizzled_viewDidAppear: 实际上调用的是原来的 viewDidAppear:

    2. 先尝试添加原 selector 是为了做一层保护,因为如果这个类没有实现 originalSelector ,但其父类实现了,那 class_getInstanceMethod 会返回父类的方法。这样 method_exchangeImplementations 替换的是父类的那个方法,这当然不是你想要的。所以我们先尝试添加 orginalSelector ,如果已经存在,再用 method_exchangeImplementations 把原方法的实现跟新的方法实现给交换掉。

    3. 类别里添加 +load: 方法,然后在 +load: 里把 viewDidAppear 给替换掉:

    4. 一般情况下,类别里的方法会重写掉主类里相同命名的方法。如果有两个类别实现了相同命名的方法,只有一个方法会被调用。但 +load: 是个特例,当一个类被读到内存的时候, runtime 会给这个类及它的每一个类别都发送一个 +load: 消息。也就是说一个类别里面实现了+load方法,就能自动消息。

    经过以上几个步骤,我们就实现了添加日志记录的解耦操作,没有动到原始类的任何代码。这样一个过程就叫AOP编程,AOP是一种思想。

    iOS业界AOP框架

    工程添加Podfile

    target 'AOP' do
    pod 'Aspects'
    end
    

    实现代码如下

    + (void)load{
        [UIViewController aspect_hookSelector:@selector(viewDidAppear:)
                                  withOptions:AspectPositionAfter
                                   usingBlock:^(id<AspectInfo>aspectInfo){
                                       [Stastic stasticWithEventName:@"UIViewController"];
                                   } error:nil];
    }
    

    AOP框架之 Aspects 打点统计

    建两个测试类Test1ViewController,Test2ViewController

    Test1ViewController.m

    #import "Test1ViewController.h"
    #import "Test2ViewController.h"
    
    @interface Test1ViewController ()
    
    @end
    
    @implementation Test1ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        self.title = @"Test1ViewController";
        self.view.backgroundColor = [UIColor redColor];
        
        UIButton *btn1 = [[UIButton alloc] initWithFrame:CGRectMake(100, 80, 100, 80)];
        [btn1 setTitle:@"Press_One" forState:UIControlStateNormal];
        btn1.backgroundColor = [UIColor redColor];
        [btn1 addTarget:self action:@selector(action1) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn1];
        
        UIButton *btn2 = [[UIButton alloc] initWithFrame:CGRectMake(300, 80, 100, 80)];
        [btn2 setTitle:@"Press_Two" forState:UIControlStateNormal];
        btn2.backgroundColor = [UIColor redColor];
        [btn2 addTarget:self action:@selector(action2) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn2];
    }
    
    - (void)viewDidAppear:(BOOL)animated{
        [super viewDidAppear:animated];
    }
    
    - (void)action1{
        Test2ViewController *vc = [[Test2ViewController alloc] init];
        [self.navigationController pushViewController:vc animated:NO];
    }
    
    - (void)action2{
        
    }
    

    Test2ViewController.m

    #import "Test2ViewController.h"
    
    @interface Test2ViewController ()
    
    @end
    
    @implementation Test2ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        self.title = @"Test2ViewController";
        self.view.backgroundColor = [UIColor greenColor];
    }
    
    - (void)viewDidAppear:(BOOL)animated{
        [super viewDidAppear:animated];
    }
    
    
    @end
    

    修改ViewController.m如下

    #import "ViewController.h"
    #import "Test1ViewController.h"
    
    
    @interface ViewController ()
    @property (nonatomic,strong)  UINavigationController *nav;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        Test1ViewController *test1 = [[Test1ViewController alloc] init];
        _nav = [[UINavigationController alloc] initWithRootViewController:test1];
        [self.view addSubview:_nav.view];
    }
    
    - (void)viewDidAppear:(BOOL)animated{
        [super viewDidAppear:animated];
    }
    
    
    @end
    

    解耦步骤:

    1. 建立AppDelegate+Stastic 类别管理所有需要统计的类跟方法。
    2. 实现一个解析统计的类
    3. 程序启动调用 [AppDelegate setupLogging];

    AppDelegate+Stastic.m

    #import "AppDelegate+Stastic.h"
    #import "DLAOP.h"
    
    @implementation AppDelegate (Stastic)
    + (void)setupLogging{
        NSDictionary *configDic = @{
                                    @"ViewController":@{
                                            @"des":@"show ViewController",
                                            },
                                    @"Test1ViewController":@{
                                            @"des":@"show Test1ViewController",
                                            @"TrackEvents":@[@{
                                                                 @"EventDes":@"click action1",
                                                                 @"EventSelectorName":@"action1",
                                                                 @"block":^(id<AspectInfo>aspectInfo){
                                                                     NSLog(@"统计 Test1ViewController action1 点击事件");
                                                                 },
                                                                 },
                                                             @{
                                                                 @"EventDes":@"click action2",
                                                                 @"EventSelectorName":@"action2",
                                                                 @"block":^(id<AspectInfo>aspectInfo){
                                                                     NSLog(@"统计 Test1ViewController action2 点击事件");
                                                                 },
                                                                 }],
                                            },
                                    @"Test2ViewController":@{
                                            @"des":@"show Test2ViewController",
                                            }
                                    };
        
        [DLAOP setUpWithConfig:configDic];
    }
    
    @end
    

    DLAOP.m

    #import "DLAOP.h"
    
    @import UIKit;
    
    typedef void (^AspectHandlerBlock)(id<AspectInfo> aspectInfo);
    
    @implementation DLAOP
    
    + (void)setUpWithConfig:(NSDictionary *)configDic{
        // hook 所有页面的viewDidAppear事件
        [UIViewController aspect_hookSelector:@selector(viewDidAppear:)
                                  withOptions:AspectPositionAfter
                                   usingBlock:^(id<AspectInfo> aspectInfo){
                                       dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                                           NSString *className = NSStringFromClass([[aspectInfo instance] class]);
                                           NSString *des = configDic[className][@"des"];
                                           if (des) {
                                              NSLog(@"%@",des);
                                           }
                                       });
                                   } error:NULL];
        
        for (NSString *className in configDic) {
            Class clazz = NSClassFromString(className);
            NSDictionary *config = configDic[className];
            
            if (config[@"TrackEvents"]) {
                for (NSDictionary *event in config[@"TrackEvents"]) {
                     SEL selekor = NSSelectorFromString(event[@"EventSelectorName"]);
                     AspectHandlerBlock block = event[@"block"];
                    
                    [clazz aspect_hookSelector:selekor
                                   withOptions:AspectPositionAfter
                                    usingBlock:^(id<AspectInfo> aspectInfo){
                                        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                                            block(aspectInfo);
                                        });
                                    }error:NULL];
                }
            }
        }
    }
    
    @end
    

    程序启动调用

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        [AppDelegate setupLogging];
        return YES;
    }
    

    具体请下载源码 Demo

    相关文章

      网友评论

        本文标题:iOS 下的AOP编程之打点统计

        本文链接:https://www.haomeiwen.com/subject/huyflxtx.html