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.
Asked
Active
Viewed 916 times
2
-
Can you post the code? – Marco Santarossa Aug 12 '16 at 07:02
-
i want to access the currently visible view controller each time when a new view controller is presented. – techcraze Aug 12 '16 at 07:09
2 Answers
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