【iOS】黑魔法 Method Swizzling 及对代理方法的 hook

iOS的runtime中有一种神奇的黑魔法: Method Swizzling,利用它可以做很多有趣的事情。

Method Swizzling 的优点

例如,假设我们的项目中有这么一个需求,需要在用户进入每个页面时进行埋点。那么我们不外乎有如下几种处理方法:
1、为每个页面的 viewWillAppear 方法都添加上埋点操作;
2、在项目中构造一个 UIViewController 的基类,在基类的 viewWillAppear 方法中实现埋点操作,项目中其他的 UIViewController 都继承自此基类;
3、为 UIViewController 添加分类,在分类中使用 Method Swizzling 对 viewWillAppear 方法进行 hook,添加埋点操作;

接下来我们依次分析每种方法的利弊。方法1等于是将相同的代码来回复制粘贴,不仅耗时,而且代码重复度过高;方法2相来来说无疑是优秀了很多,极大减少了代码量,不过这种方案对项目原有代码影响较大,比较适用于项目初期,如果项目已经进行到一定程度,替换基类也会是一个不小的工作量。而方法3不仅代码量少,而且对项目原有代码的影响小,称得上是最佳方案。

简单的hook

接下来我们先来讲讲如何对 viewWillAppear 方法进行hook。代码如下:

#import "UIViewController+Tracking.h"
#import <objc/runtime.h>

@implementation UIViewController (Tracking)

+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method originalMethod = class_getInstanceMethod(self, @selector(viewWillAppear:));
        Method swizzledMethod = class_getInstanceMethod(self, @selector(hook_viewWillAppear:));
        method_exchangeImplementations(originalMethod, swizzledMethod);
    });
}

- (void)hook_viewWillAppear:(BOOL)animated
{
    NSLog(@"开始埋点");
    [self hook_viewWillAppear:animated];
}

@end

load 方法是在整个文件被添加到 runtime 时开始执行,父类最先执行,然后是子类,最后是 Category,所以我们把 hook 代码写在 load 方法里,可以保证在类首次被调用前我们 hook 掉的方法已经变成了我们所想要的实现。dispatch_once 这个 GCD 块在这里的作用是保证这份代码在程序运行过程中只会执行一次。在 hook_viewWillAppear 这个方法中,我们可以实现我们需求中的埋点功能,最后再调用原始的方法实现。这里需要注意的是,由于方法交换已经生效,所以我们最后的[self hook_viewWillAppear:animated]实际上就是在调用原始方法实现。

对代理方法进行 hook

以上是利用 Method Swizzling 对方法进行 hook 的步骤。但是我们在开发过程中可能还会遇到一些特殊的情况,需要对代理方法进行 hook,这时候又该怎么做呢?下面我用一个例子来讲解一下。假如我们有一个需求,需要在工程中监控所有 UIWebview 中的请求,当发现请求链接中含有某个域名时将该 url 上报给服务端。这时我们第一时间想到的一定就是在项目里所有 UIWebView 的代理方法中去拦截,但是如果需求中所指的网页包含我们所使用的 SDK 呢, 又或者说假如我们是 SDK 的提供方,想要监控使用我们 SDK 的 app 中的 UIWebView 的网络请求呢?这时,我们想要拿到所有 UIWebView 的代理方法似乎成为了不可能。这个时候就到了 Method Swizzling 发挥作用的时刻了。

至于如何实现,这里先贴上代码供大家参考。

#import "UIWebView+Tracking.h"
#import <objc/runtime.h>

@implementation UIWebView (Tracking)

#pragma mark - load

+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method oldMethod = class_getInstanceMethod([self class], @selector(setDelegate:));
        Method newMethod = class_getInstanceMethod([self class], @selector(hook_setDelegate:));
        method_exchangeImplementations(oldMethod, newMethod);
    });
}

#pragma mark - 交换代理方法

- (void)hook_setDelegate:(id<UIWebViewDelegate>)delegate
{
    SEL oldSelector = @selector(webView:shouldStartLoadWithRequest:navigationType:);
    SEL newSelector = @selector(hook_webView:shouldStartLoadWithRequest:navigationType:);
    Method oldMethod_del = class_getInstanceMethod([delegate class], oldSelector);
    Method oldMethod_self = class_getInstanceMethod([self class], oldSelector);
    Method newMethod = class_getInstanceMethod([self class], newSelector);

    // 若未实现代理方法,则先添加代理方法    
    BOOL isSuccess = class_addMethod([delegate class], oldSelector, class_getMethodImplementation([self class], newSelector), method_getTypeEncoding(newMethod));
    if (isSuccess) {
        class_replaceMethod([delegate class], newSelector, class_getMethodImplementation([self class], oldSelector), method_getTypeEncoding(oldMethod_self));
    } else {
        // 若已实现代理方法,则添加 hook 方法并进行交换
        BOOL isVictory = class_addMethod([delegate class], newSelector, class_getMethodImplementation([delegate class], oldSelector), method_getTypeEncoding(oldMethod_del));
        if (isVictory) {
            class_replaceMethod([delegate class], oldSelector, class_getMethodImplementation([self class], newSelector), method_getTypeEncoding(newMethod));
        }
    }
    [self hook_setDelegate:delegate];
}

#pragma mark - 交换的方法

// 原始方法实现
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    return YES;
}

// hook后的方法
- (BOOL)hook_webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if ([request.URL.host rangeOfString:@"baidu.com"].location != NSNotFound) {
        NSLog(@"拦截到的url为 : %@", request.URL);
    }
    return [self hook_webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
}

这里我们是在设置代理时拿到 delegate 所属的类,随后对该类中的- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType方法进行 hook。

问题

要使用该方法有一个前提就是 UIWebView 必须设置了代理,否则无法确定代理方法所在的类,也就无法进行 hook 了。这里我暂时还没有想到更好的办法,如果各位读者想到了更好的方法欢迎一起讨论。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容