最近在做自己的framework静态库,需要用到支付宝和微信支付,支付回调又是在Appdelegate中拿到 所以想找一种替代或者说捕获Appdelegate声明周期的方法,苦寻之后发现有大神处理过类似的事情,所以就尝试了一下,首先感谢大神的文章。
文章地址:(http://www.cnblogs.com/lonkiss/p/6492385.html)
在使用过程中也遇到一些问题,主要是hook的类根据使用方式不同导致的(其实找了很久原因),以下内容做记录使用:
主要是使用Runtime的
objc_getClass、
class_addMethod、
class_getMethodImplementation、
class_getInstanceMethod、
method_exchangeImplementations
等方法
1、SDK中创建继承自NSObject的XXX_HookObject文件
2、.m中实现方法
- (void)hookMehod:(SEL)oldSEL andDef:(SEL)defaultSEL andNew:(SEL)newSEL {
NSLog(@"hookMehod");
Class oldClass = objc_getClass([@"AppDelegate" UTF8String]);
Class newClass = [CYX_HookUtils class];
//把方法加给原Class
class_addMethod(oldClass, newSEL, class_getMethodImplementation(newClass, newSEL), nil);
class_addMethod(oldClass, oldSEL, class_getMethodImplementation(newClass, defaultSEL),nil);
Method oldMethod = class_getInstanceMethod(oldClass, oldSEL);
assert(oldMethod);
Method newMethod = class_getInstanceMethod(oldClass, newSEL);
assert(newMethod);
method_exchangeImplementations(oldMethod, newMethod);
}
+ (void)load {
NSLog(@"load");
[self hookMehod:@selector(application:didFinishLaunchingWithOptions:) andDef:@selector(defaultApplication:didFinishLaunchingWithOptions:) andNew:@selector(hookedApplication:didFinishLaunchingWithOptions:)];
[self hookMehod:@selector(applicationWillEnterForeground:) andDef:@selector(defaultApplicationWillEnterForeground:) andNew:@selector(hookedApplicationWillEnterForeground:)];
}
/*具体要走的代码*/
-(BOOL)hookedApplication:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)dic
{
NSLog(@"applicationDidFinishLaunching");
[self hookedApplication:application didFinishLaunchingWithOptions:dic];
return YES;
}
- (void)hookedApplicationWillResignActive:(UIApplication *)application {
[self hookedApplicationWillResignActive:application];
}
- (void)hookedApplicationDidEnterBackground:(UIApplication *)application {
[self hookedApplicationDidEnterBackground:application];
}
- (void)hookedApplicationWillEnterForeground:(UIApplication *)application {
[self hookedApplicationWillEnterForeground:application];
}
- (void)hookedApplicationDidBecomeActive:(UIApplication *)application {
[self hookedApplicationDidBecomeActive:application];
}
- (void)hookedApplicationWillTerminate:(UIApplication *)application {
[self hookedApplicationWillTerminate:application];
}
原作者使用了Adobe框架,所以会出现无法找到要hook的类问题,如果仅是在SDK中Hook Appdelegate生命周期则直接将原文档中的
Class oldClass = objc_getClass([@"CTAppDelegate" UTF8String]);
更改获取Appdelegate类
Class oldClass = objc_getClass([@"AppDelegate" UTF8String]);
且无需在主动调用Appdelegate,讲hook文件直接放到SDK中即可使用(NSObject会自动调用类方法
+ (void)load
主要问题解决了,其他的就是如何继承支付宝和微信SDK问题了
再次感谢原作者
原出处(http://www.cnblogs.com/lonkiss/p/6492385.html)