Objective-C的hook方案/ Method Swizzling

时间:2022-07-23
本文章向大家介绍Objective-C的hook方案/ Method Swizzling,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Method Swizzling

Method Swizzling是改变一个selector的实际实现的技术。通过这一技术,我们可以在运行时通过修改类的分发表中selector对应的函数,来修改方法的实现。

实现

以关闭推送为例 通过swizzleSelector,替换UIApplication的【registerForRemoteNotifications】方法,让它没法实现,实现整体关闭推送信息功能

static inline void JJ_swizzleSelector(Class class, SEL originalSelector, SEL swizzledSelector) {
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    if (class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))) {
        class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}
@implementation UNUserNotificationCenter(Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];
        JJ_swizzleSelector(class, @selector(requestAuthorizationWithOptions:completionHandler:), @selector(hook_requestAuthorizationWithOptions));
    });
}
-(void)hook_requestAuthorizationWithOptions
{
    //关闭通知
}
@end