iOS: How to achieve behavior like Android’s startActivityForResult

print
https://stackoverflow.com/questions/13013476/ios-how-to-achieve-behavior-like-androids-startactivityforresult

 

 

There are a couple ways, so mostly you do this yourself with various patterns. You can set up a navigation controller in the app delegate as follows:

self.viewController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];
self.navigationController = [[ UINavigationController alloc ] initWithRootViewController:self.viewController ];
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];

Then when you want to present a new vc you can do this:

OtherViewController *ovc = [[ OtherViewController alloc ] initWithNibName:@"OtherViewController" bundle:nil ];
[ self.navigationController pushViewController:ovc animated:YES ];

To go back do this:

[ self.navigationController popViewControllerAnimated:YES ];

As far as a callback goes one way to do this is to make a protocol like this somewhere in your project:

@protocol AbstractViewControllerDelegate <NSObject>

@required
- (void)abstractViewControllerDone;

@end

Then make each view controller you want a callback to be triggered in a delegate aka:

 @interface OtherViewController : UIViewController <AbstractViewControllerDelegate>

 @property (nonatomic, assign) id<AbstractViewControllerDelegate> delegate;

 @end

Finally when you present a new vc assign it as a delegate:

  OtherViewController *ovc = [[ OtherViewController alloc ] initWithNibName:@"OtherViewController" bundle:nil ];
  ovc.delegate = self;
  [ self.navigationController pushViewController:ovc animated:YES ];

then when you dismiss the ovc, make this call

 [self.delegate abstractViewControllerDone];
 [ self.navigationController popViewControllerAnimated:YES ];

And in the rootVC, which conforms to the protocol you made, you just fill out this method:

 -(void) abstractViewControllerDone {

 }

That you just made a call to. This requires a lot of setup but other options include looking into NSNotifications and blocks which can be simpler depending on what your doing.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.