zoukankan      html  css  js  c++  java
  • Hook~iOS用钩子实现代码注入(埋点方案)

    想要为某各类添加钩子首先要建立这个类或父类的分类,运用runtime的方法交换的方法实现交换再调回原方法 这就是钩子的基本思路  运用lldb 查看方法的调用堆栈 就可以找到在这个方法之前调用的方法,然后我们拦截它,交换它!

    lldb 的命令 thread backtrace  查看调用堆栈

    找到你需要的拦截的方法

        Method applicationLanch = class_getInstanceMethod([self class],@selector(application: didFinishLaunchingWithOptions:));

        Method newApplicationLanch = class_getInstanceMethod([self class], @selector(configurationApplication: didFinishLaunchingWithOptions:));

        method_exchangeImplementations(applicationLanch, newApplicationLanch);

    然后调回本身:

    - (BOOL)configurationApplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

        BOOL result = [self configurationApplication:application didFinishLaunchingWithOptions:launchOptions];

        NSLog(@"%@AppDelegate+Hook",

              [self class]);

        return result;

    }

    注意这两个方法已经交换所以实际调用的是application: didFinishLaunchingWithOptions: 这个方法,那么代理方法怎么拦截呢?

    也是一样的只要拦截 交换setDelegate: 方法 在交换的方法中遵守代理 然后在这个方法里继续交换你想要交换的方法

    #define GET_CLASS_CUSTOM_SEL(sel,class)  NSSelectorFromString([NSString stringWithFormat:@"%@_%@",NSStringFromClass(class),NSStringFromSelector(sel)])

    - (void)fd_setDelegate:(id<UIScrollViewDelegate>)delegate {

        if ([self isMemberOfClass:[UIScrollView class]]) {

            if (![self isContainSel:GET_CLASS_CUSTOM_SEL(@selector(scrollViewWillBeginDragging:),[delegate class]) inClass:[delegate class]]) {

                [self swizzling_scrollViewWillBeginDragging:delegate];

            }

            [self fd_setDelegate:delegate];

        }

    }

    - (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;

    }

    挥毫泼墨,书写人生篇章
  • 相关阅读:
    MS SQL 事物日志传送能否跨数据库版本吗?
    MS SQL 模仿ORACLE的DESC
    Rhel-Server 5.5 安装ORACLE10
    ORACLE约束总结
    Win2003 设置远程连接限制数
    javascript学习代码-判断闰年
    javascript学习代码--点击按钮显示内容
    javascript学习代码
    反馈表样式
    调查表样式设计
  • 原文地址:https://www.cnblogs.com/Jusive/p/6943709.html
Copyright © 2011-2022 走看看