Get the presented Viewcontroller from ReactNative rootviewcontroller
Asked Answered
O

1

9

In React Native project I want to access the Presented Viewcontroller from iOS npm module. I'm able to access the rootviewcontroller of the RN project using the below code

UIViewController *vc = [UIApplication sharedApplication].delegate.window.rootViewController;

But I want the current VC that is presented on top of RootVC so that I should be able to present native(iOS) UINavigationController on top of it.

Note:[UIApplication sharedApplication].delegate.window.rootViewController.presentedViewController returns nill.

Onetime answered 12/12, 2017 at 4:52 Comment(0)
N
12

I know this was asked a long time ago, but I was running into the same problem today ([UIApplication sharedApplication].delegate.window.rootViewController.presentedViewController returns nil) and couldn't find the solution for a while, so I'll leave this here for anyone still looking.

There's a function in the React Native source code that allows you to determine the presented view controller. It seems like they use this for their ActionSheetIOS module (see this line). To use this in your own native module, add the following:

// Put this near the top of the file
#import <React/RCTUtils.h>

...

// Put this where you need access to the presented view controller
UIViewController *presentedViewController = RCTPresentedViewController();
Nitpicking answered 19/8, 2019 at 19:35 Comment(1)
Note that if you want to access RCTPresentedViewController in Swift, you can add the #import <React/RCTUtils.h> line to your <ModuleName>-Bridging-Header.h file.Gallows

© 2022 - 2024 — McMap. All rights reserved.