1.需要WMAppDelegateProxy类
@interfaceWMAppDelegateProxy :NSProxy
- (id)init;
@property(nonatomic,strong)NSObject *hjAppDelegate;
@property(nonatomic,strong)NSObject *originalAppDelegate;
@end
#import"WMAppDelegateProxy.h"
@implementationWMAppDelegateProxy
- (id)init
{
returnself;
}
- (NSMethodSignature*)methodSignatureForSelector:(SEL)aSelector
{
NSMethodSignature*sig;
sig = [self.originalAppDelegatemethodSignatureForSelector:aSelector];
if(sig) {
returnsig;
}else{
sig = [self.hjAppDelegatemethodSignatureForSelector:aSelector];
returnsig;
}
returnnil;
}
// Invoke the invocation on whichever real object had a signature for it.
- (void)forwardInvocation:(NSInvocation*)invocation
{
if([selfhjDelegateRespondsToSelector:[invocationselector]]) {
[invocationinvokeWithTarget:self.hjAppDelegate];
}
if([self.originalAppDelegatemethodSignatureForSelector:[invocationselector]]) {
[invocationinvokeWithTarget:self.originalAppDelegate];
}
}
// Override some of NSProxy's implementations to forward them...
- (BOOL)respondsToSelector:(SEL)aSelector
{
if([self.hjAppDelegaterespondsToSelector:aSelector])
returnYES;
if([self.originalAppDelegaterespondsToSelector:aSelector])
returnYES;
returnNO;
}
- (BOOL)hjDelegateRespondsToSelector:(SEL)selector
{
return[self.hjAppDelegaterespondsToSelector:selector] && ![[NSObjectclass]instancesRespondToSelector:selector];
}
@end
2.新建WMAppDelegate类
#import
@interfaceWMAppDelegate :NSObject
@end
#import"WMAppDelegate.h"
@implementationWMAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//如果sdk初值化是在didFinishLaunchingWithOptions方法,就无法运行到sdk里面的这个方法
NSLog(@"SDK UIApplication didFinishLaunchingWithOptions:%@, %@", application, launchOptions);
returnYES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
}
- (void)applicationWillEnterForeground:(UIApplication*)application {
}
- (void)applicationDidBecomeActive:(UIApplication*)application {
}
- (void)applicationWillTerminate:(UIApplication*)application {
}
@end
3.在SDK初值化的时候 添加如下代码
_appDelegateProxy=[[WMAppDelegateProxyalloc]init];
@synchronized([UIApplicationsharedApplication]) {
_appDelegateProxy.hjAppDelegate= [[WMAppDelegatealloc]init];
_appDelegateProxy.originalAppDelegate= [UIApplicationsharedApplication].delegate;
[UIApplicationsharedApplication].delegate=_appDelegateProxy;
}
原理:
[UIApplication sharedApplication].delegate, 这个delegate默认是指向DemoAppDelegate, 现在我们可以把[UIApplication sharedApplication].delegate指向一个变量proxy, 那么这个变量将会获取到所有原来应用AppDelegate的回调方法, 其中包括appDidFinishLaunchedWithOption, appWillResignActive, appWillEnterForeground等回调用, 同样也包括本地通知以及远程通知调用时的回调。
上面这个方法是把这个[UIApplication sharedApplication].delegate指向一个变量proxy, 我们只需要在proxy这个变量中同时把appDelegate也进行调用就可以了。 也即在proxy中,我们可以先处理一下我们想处理的回调方法, 然后继续让这些回调方法继续流转, 如流转到appDelegate即可。也即让自己先处理完成后, 再进行消息的转发。