iOS学习笔记iOS开发记录

Objective-C的hook方案/ Method Swizz

2020-08-05  本文已影响0人  freesan44

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
上一篇下一篇

猜你喜欢

热点阅读