美文网首页iOS面试iOS开发技巧
iOS-无侵入的埋点方案

iOS-无侵入的埋点方案

作者: 海文_L | 来源:发表于2020-08-26 16:19 被阅读0次

    前言

    埋点统计在产品运营过程中对用户行为分析、产品前期的业务模式探索起着很重要的作用。常用的三种埋点方式主要包括手动埋点、可视化埋点和无痕埋点。

    • 手动埋点主要是通过手写代码的方式哪里需要埋哪里,优点是数据精准、方便调试、能够自定义所需的变量值,缺点是工作量较大、埋点代码多容易产生冗余、后期难维护等;

    • 可视化埋点指前端或者APP端基于DOM元素和控件所精准自动埋点的上报的方案,优点是相比较于无埋点相而言对较低,但是这个可视化元素的识别技术是客户端或者前端所要实现的,唯一 ID 生成也无需客户端去自定义规则,这套生成规则由相关产品在自动化工具的情况下生成配置表,下发到客户端,再由客户端按坑就班到相关界面去实现、数据量相对精确。缺点是可视化工具的平台的搭建,静态页面的元素识别都需要额外开发、动态效果可能会遗漏。(可参考:可视化埋点(2):iOS端实现

    • 无痕埋点指的是通过编译工具、预编译替换代码等,直接由SDK全部负责采集上报,优点是代码不会出现在业务代码中、容易管理和维护,缺点是后期的结息比较复杂、view_path不能做到100%唯一、后端或产品人员数据分析工作量大。

    三种埋点方案中,可视化埋点和无痕埋点,都属于无侵入的埋点方案,因为它们都不需要在业务代码中写入埋点代码。采用无侵入埋点方案,既可以做到埋点被统一维护,又可以实现和工程代码的解耦。其中无痕埋点方案能够满足大多数应用的埋点需求。

    无痕埋点方案介绍

    最常见的三种埋点类型有页面进入次数、页面停留时间、点击事件。对于这三种常见的情况,我们都可以通过runtimemethod swizzling来插入埋点代码,以实现无侵入的埋点方法,可分三步来处理:实现替换、生成唯一标识、数据上报。

    新建一个方法替换类NSObject+Logger,加上替换的方法swizzleSelectorFromSelector : toSelector :,代码如下:

    + (void)swizzleSelectorFromSelector:(SEL)originalSelector toSelector:(SEL)swizzledSelector {
       Method originalMethod = class_getInstanceMethod(self, originalSelector);
       Method swizzledMethod = class_getInstanceMethod(self, swizzledSelector);
    
       BOOL didAddMethod =
       class_addMethod(self,
                       originalSelector,
                       method_getImplementation(swizzledMethod),
                       method_getTypeEncoding(swizzledMethod));
    
       if (didAddMethod) {
           class_replaceMethod(self,
                               swizzledSelector,
                               method_getImplementation(originalMethod),
                               method_getTypeEncoding(originalMethod));
      } else {
           method_exchangeImplementations(originalMethod, swizzledMethod);
      }
    }
    

    这个方法利用运行时method_exchangeImplementations接口将方法的实现进行了交换,原方法调用时就会被hook住,从而去执行指定的方法。

    页面进入次数、页面停留时间事件

    页面进入次数、页面停留时间需要对UIViewController生命周期进行埋点,可以创建一个UIViewControllerCategory,通过NSObject+Logger将原生方法替换,代码如下:

    + (void)load {
      static dispatch_once_t onceToken;
      dispatch_once(&onceToken, ^{
          Class class = NSClassFromString(@"UIViewController");
          [class swizzleSelectorFromSelector:@selector(viewWillAppear:) toSelector:@selector(hook_viewWillAppear:)];
          [class swizzleSelectorFromSelector:@selector(viewWillDisappear:) toSelector:@selector(hook_viewWillDisappear:)];
      });
    }
    ​
    - (void)hook_viewWillAppear:(BOOL)animated {
      //先执行插入代码,再执行原 viewWillAppear 方法
      [self insertToViewWillAppear];
    
      [self hook_viewWillAppear:animated];
    }
    ​
    - (void)hook_viewWillDisappear:(BOOL)animated {
      //先执行插入代码,再执行原 viewWillDisappear 方法
      [self insertToViewWillDisappear];
    
      [self hook_viewWillDisappear:animated];
    }</pre>
    
    数据上报部分这里没有做具体介绍,可以自行对接自己的后端接口或者一些第三方平台,如友盟。
    
    ## 点击事件
    
    常用的控件如UIButton、UITextField、UISwitch、UISegmentedControl、UISlider 等,它们的父类都是UIControl ,我们可对sendAction:to:forEvent: 进行拦截,代码如下:
    
    <pre spellcheck="false" class="md-fences md-end-block contain-cm modeLoaded" lang="" contenteditable="false" cid="n36" mdtype="fences" style="caret-color: rgb(0, 0, 0); color: rgb(0, 0, 0); font-style: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: auto; text-indent: 0px; text-transform: none; widows: auto; word-spacing: 0px; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; text-decoration: none; box-sizing: border-box; overflow: visible; font-family: Consolas, &quot;Liberation Mono&quot;, Courier, monospace; font-size: 0.9em; white-space: normal; display: block; break-inside: avoid; text-align: left; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); border: 1px solid rgb(223, 226, 229); border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; padding: 8px 1em 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; position: relative !important;">+ (void) load {
      static dispatch_once_t onceToken;
      dispatch_once(&onceToken, ^{
          //可监听到UIButton、UITextField、UISwitch、UISegmentedControl、UISlider 、UIStepper等控件的Action事件
          [self swizzleSelectorFromSelector:@selector(sendAction:to:forEvent:) toSelector:@selector(hook_sendAction:to:forEvent:)];
      });
    }
    ​
    #pragma mark--
    #pragma 按钮点击
    - (void)hook_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
      [self insertToSendAction:action to:target forEvent:event];
    
      [self hook_sendAction:action to:target forEvent:event];
    }
    ​
    - (void)insertToSendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
      //日志记录
      if ([[[event allTouches] anyObject] phase] == UITouchPhaseEnded) {
          NSString *actionString = NSStringFromSelector(action);
          NSString *targetString = NSStringFromClass([target class]);
    
          NSLog(@"唯一标识:%@_%@_%@", targetString, self.accessibilityIdentifier, actionString);
      }
    }
    

    唯一标识

    这里的唯一标识组成规则是NSStringFromClass([target class])+self.accessibilityIdentifieraccessibilityIdentifier+NSStringFromSelector(action)accessibilityIdentifier系统默认为nil,我们需要根据不同控件的特性为accessibilityIdentifier进行赋值,如UIButton控件的accessibilityIdentifier可以是控件的变量名,考虑到用XIBSB布局不一定会定义变量,可取buttontitle值或者image的名字来定义,新建一个UIView+Logger类:

    @implementation UIView (Logger)
    ​
    + (void)load {
      static dispatch_once_t onceToken;
      dispatch_once(&onceToken, ^{        
          Class class = NSClassFromString(@"UIView");
          [class swizzleSelectorFromSelector:@selector(accessibilityIdentifier) toSelector:@selector(hook_accessibilityIdentifier)];
      });
    }
    ​
    #pragma mark - Method Swizzling
    - (NSString *)hook_accessibilityIdentifier {
      NSString *labelStr = [self.superview findNameWithInstance:self];
    
      if (labelStr && ![labelStr isEqualToString:@""]) {
          //SB或XIB布局的,因获取不到image的name,所以至少要拉个变量名
          labelStr = [NSString stringWithFormat:@"%@",labelStr];
      } else {
          if ([self isKindOfClass:[UIButton class]]) {
              //UIButton 使用 button 的 text 和 image
              labelStr = [NSString stringWithFormat:@"%@%@",((UIButton *)self).titleLabel.text?:@"",((UIButton *)self).imageView.image.accessibilityIdentifier?:@""];
          }
      }
    
      [self setAccessibilityIdentifier:labelStr];
      return labelStr;
    }
    ​
    @end
    

    findNameWithInstance:的实现

    - (NSString *)findNameWithInstance:(UIView *)instance
    {
      id nextResponder = [self nextResponder];
      NSString *name = [RuntimeHelper nameWithClass:self instance:instance];
      if (!name) {
          return [nextResponder findNameWithInstance:instance];
      }
    ​
      if ([name hasPrefix:@"_"]) { //去掉变量名的下划线前缀
          name = [name substringFromIndex:1];
      }
    ​
      return name;
    }
    

    这里又延伸出了一个问题,UIImage 并没有提供获取资源名字的方法。解决问题的方式是通过替换 UIImageimageNamed: 方法对 UIImageaccessibilityIdentifier 进行赋值:

    @implementation UIImage (Logger)
    + (void)load {
      static dispatch_once_t onceToken;
      dispatch_once(&onceToken, ^{        
          Class imageClass = NSClassFromString(@"UIImage");
          [object_getClass(imageClass) swizzleSelectorFromSelector:@selector(imageNamed:) toSelector:@selector(hook_imageNamed:)];
      });
    }
    ​
    + (UIImage *)hook_imageNamed:(NSString *)imageName {
      UIImage *image = [UIImage hook_imageNamed:imageName];
      image.accessibilityIdentifier = imageName;
      return image;
    }
    

    Delegate事件

    Delegate 事件的 swizzling 需要分成两步,第一步先替换掉 setDelegate: ,其次是对 Delegate 事件的替换,举个 UIScrollView 的例子:

    //我们要保证在每个控制器里都执行一次,所以替换的方法都会加上class name的前缀,以示区别
    #define GET_CLASS_CUSTOM_SEL(sel,class) NSSelectorFromString([NSString stringWithFormat:@"%@_%@",NSStringFromClass(class),NSStringFromSelector(sel)])
    ​
    @implementation UIScrollView (Logger)
    + (void)load {
      static dispatch_once_t onceToken;
      dispatch_once(&onceToken, ^{
          [[self class] swizzleSelectorFromSelector:@selector(setDelegate:) toSelector:@selector(hook_setDelegate:)];
      });
    }
    ​
    - (void)hook_setDelegate:(id<UIScrollViewDelegate>)delegate {
      // 由于setDelegate方法可能被多次调用,所以要判断是否已经swizzling了,防止重复执行。
      if (![[self class] delegate:delegate isContain:@selector(scrollViewWillBeginDragging:)]) {
          [self hook_scrollViewWillBeginDragging:delegate];
      }
    
      if ([NSStringFromClass([self class]) isEqualToString:@"UITableView"]){
          if (![[self class] delegate:delegate isContain:@selector(tableView:didSelectRowAtIndexPath:)]) {
              [(UITableView *)self hook_tableViewDidSelectRowAtIndexPathInClass:delegate];
          }
      }
      [self hook_setDelegate:delegate];
    }
    ​
    #pragma --
    #pragma UIScrollViewDelegate
    - (void)hook_scrollViewWillBeginDragging:(id<UIScrollViewDelegate>)delegate {
      [[self class] swizzleDelegate:delegate originSelector:@selector(scrollViewWillBeginDragging:) swizzleSelector:@selector(insertToScrollViewWillBeginDragging:)];
    }
    ​
    - (void)insertToScrollViewWillBeginDragging:(UIScrollView *)scrollView {
      SEL sel = GET_CLASS_CUSTOM_SEL(@selector(scrollViewWillBeginDragging:),[self class]);
      if ([self respondsToSelector:sel]) {
          IMP imp = [self methodForSelector:sel];
          void (*func)(id, SEL,id) = (void *)imp;
    
          NSLog(@"标识:%@_%@_%@", NSStringFromClass([self class]), [RuntimeHelper nameWithClass:self instance:scrollView], NSStringFromSelector(@selector(scrollViewWillBeginDragging:)));
    
          func(self, sel, scrollView);
      }
    }
    

    NSObject+Logger类新增 delegate: isContain:swizzleDelegate: originSelector: swizzleSelector:两个方法,完整代码如下:

    #define GET_CLASS_CUSTOM_SEL(sel,class) NSSelectorFromString([NSString stringWithFormat:@"%@_%@",NSStringFromClass(class),NSStringFromSelector(sel)])
    ​
    @implementation NSObject (Logger)
    + (void)swizzleSelectorFromSelector:(SEL)originalSelector toSelector:(SEL)swizzledSelector {
      Method originalMethod = class_getInstanceMethod(self, originalSelector);
      Method swizzledMethod = class_getInstanceMethod(self, swizzledSelector);
    ​
    //   NSLog(@"__delegateObject %@", [self class]);
    ​
      BOOL didAddMethod =
      class_addMethod(self,
                      originalSelector,
                      method_getImplementation(swizzledMethod),
                      method_getTypeEncoding(swizzledMethod));
    ​
      if (didAddMethod) {
          class_replaceMethod(self,
                              swizzledSelector,
                              method_getImplementation(originalMethod),
                              method_getTypeEncoding(originalMethod));
      } else {
          method_exchangeImplementations(originalMethod, swizzledMethod);
      }
    }
    ​
    + (BOOL)delegate:(id)delegateObject isContain:(SEL)selector {
      return [self isContainSel:GET_CLASS_CUSTOM_SEL(selector, [delegateObject class]) inClass:[delegateObject class]];
    }
    ​
    + (void)swizzleDelegate:(id)delegateObject originSelector:(SEL)originSelector swizzleSelector:(SEL)swizzleSelector {
      SEL newSelector = GET_CLASS_CUSTOM_SEL(originSelector, [delegateObject class]);
      Method swizzledMethod = class_getInstanceMethod([delegateObject class], swizzleSelector);
    
      //增加swizzle delegate method
      class_addMethod([delegateObject class],
                      newSelector,
                      method_getImplementation(class_getInstanceMethod([self class], swizzleSelector)),
                      method_getTypeEncoding(swizzledMethod));
    
      Method swizzleDelegateMethod = class_getInstanceMethod([delegateObject class], newSelector);
      Method originDelegateMethod = class_getInstanceMethod([delegateObject class], originSelector);
    
      // 将swizzle delegate method 和 origin delegate method 交换
      method_exchangeImplementations(swizzleDelegateMethod, originDelegateMethod);
    }
    ​
    + (BOOL)isContainSel:(SEL)sel inClass:(Class)class {
      unsigned int count;
    
      Method *methodList = class_copyMethodList(class,&count);
      for (int i = 0; i < count; i++) {
          Method method = methodList[i];
          NSString *tempMethodString = [NSString stringWithUTF8String:sel_getName(method_getName(method))];
          if ([tempMethodString isEqualToString:NSStringFromSelector(sel)]) {
              return YES;
          }
      }
      return NO;
    }
    

    数据上报的方式这里没有做过多的介绍,可通过集成第三方统计平台或自搭服务进行对接,完整的DEMO参考这里

    参考文献:

    可视化埋点(1):思路

    iOS无埋点数据统计实践

    相关文章

      网友评论

        本文标题:iOS-无侵入的埋点方案

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