2

I am new to iOS development. I am stuck in a problem where my use case is to get callback each time when the rootviewcontroller of UIWindow changes. I know there is a rootviewcontroller.tansiondelegate delegate property in rootviewcontroller but i am unable to get callback after using this delegate.

techcraze
  • 112
  • 1
  • 10

2 Answers2

1

you can use the KVO to observe the change of property. like:

[[UIApplication sharedApplication].keyWindow addObserver:self forKeyPath:@"rootViewController" options:NSKeyValueObservingOptionNew context:@"rootViewControllerChange"];

and when the rootViewController is changed, will call method:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([(__bridge NSString *)context isEqualToString:@"rootViewControllerChange"] ) {
        // code what you want to do...
    }
}

NOTE:

Don't forget to remove this observer when the instance of [self class] dealloc.

[[UIApplication sharedApplication].keyWindow removeObserver:self forKeyPath:@"rootViewController" context:@"rootViewControllerChange"];

if it is not working:

There is a more stupid method:☔️

you can use NSNotificationCenter, when you present a controller, you can

[[NSNotificationCenter defaultCenter] postNotificationName:@"PushNotificationPresentedController" object:nil userInfo:nil];

and addObserver to receive this Notification where you want to callback:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didPresentedController) name:@"PushNotificationPresentedController" object:nil]; 

(if i have another better method, i will update my answer.)

ocarol
  • 283
  • 1
  • 5
  • it is not working. Are you sure the rootviewcontroller is KVO compliant? – techcraze Aug 12 '16 at 08:34
  • that will surely work. But in my use case i do not know the view controller in advance. so i have to play with rootview controller only. you can refer the link posted in my answer for more fun on this topic – techcraze Aug 12 '16 at 09:37
0

Got it working. I used method swizzling for this. Very useful concept. Please refer this for method swizzling technique. Refer this for similar question.

Community
  • 1
  • 1
techcraze
  • 112
  • 1
  • 10