Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Current View Controller from NSObject Class file

Tags:

ios

I have an NSObject file for detecting network connection. If its down, I will like to display an activity indicator at the top of the current view controller navigationitem. My storyboard config is a tabbarcontroller with three tabs. Each tab connect to multiple viewcontrollers through a navigation controller individually (i.e. each tab got one navigation controller).

I like to get current viewcontroller and display the activity indicator but failed to get e current display viewcontroller. I have tried the codes below but doesnt work. Can anyone advice me?

   UIViewController *topViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
   UIActivityIndicatorView *aiView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
   aiView.hidesWhenStopped = NO; //I added this just so I could see it
   topViewController.navigationItem.titleView = aiView;
like image 651
user2981756 Avatar asked Dec 08 '22 08:12

user2981756


1 Answers

You can try this. I used this to display a view anywhere in my app from a NSObject file:

UIWindow *window=[UIApplication sharedApplication].keyWindow;
UIViewController *vc = [window rootViewController];
like image 86
Chris Avatar answered Feb 02 '23 01:02

Chris