美文网首页iOS学习笔记iOS开发记录
Objective-C的hook方案/ Method Swizz

Objective-C的hook方案/ Method Swizz

作者: freesan44 | 来源:发表于2020-08-05 09:38 被阅读0次

    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
    

    相关文章

      网友评论

        本文标题:Objective-C的hook方案/ Method Swizz

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