IOS实现hook的功能,拦截UINavigati…

在应用中有时候需要对页面跳转做控制,如:是否有网络,是否有访问权限等。
在IOS实现hook的功能,拦截UINavigationController的页面跳转pushViewController方法
在页面公共代码 viewDidLoad中添加如下代码

    //================

   Method sendEvent = class_getInstanceMethod([UINavigationController class], @selector(pushViewController: animated:));

   Method sendEventMySelf = class_getInstanceMethod([self class], @selector(sendEventHooked:animated:));

    

    // 将目标函数的原实现绑定到sendEventOriginalImplemention方法上

   IMP sendEventImp = method_getImplementation(sendEvent);

   class_addMethod([UINavigationController class], @selector(myPushViewController: animated:), sendEventImp, method_getTypeEncoding(sendEvent));

    

    // 然后用我们自己的函数的实现,替换目标函数对应的实现

   IMP sendEventMySelfImp = method_getImplementation(sendEventMySelf);

   class_replaceMethod([UINavigationController class], @selector(pushViewController: animated:), sendEventMySelfImp, method_getTypeEncoding(sendEvent));

    //===========================


实现HOOK方法,既可以拦截对应的方法,添加业务操作后,再调用原有方法

 

- (void)sendEventHooked:(UIViewController *)view animated:(BOOL)anim

{

    // do something what ever you want

    NSLog(@"!!!!!!!===============haha, this is my self sendEventMethod!!!!!!!");

    //NSValue *value = [[NSValue alloc] ];

    [self performSelector:@selector(myPushViewController:animated:) withObject:view withObject:nil];

}

你可能感兴趣的:(IOS基础)