Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send notification to another view controller when request finishes

I am working on an Iphone Application (ios5 + storyboard + arc). I have 2 ViewControllers A and B.

In A I have a button. when pressed I am submitting a request asynchronously to the server (using AFNetworking) and I will go to View Controller B by using performSegueWithIdentifier (push not modal).

When the request finishes it executes a request successful Block that will save data to the database. (The block is in ViewController A since the request is sent from there)

Is there a way I can notify ViewController B that the request has finished and execute a method in B?

What I'm looking for is that when the request finishes and enters the Success Block I run a method in view controller B which is the loaded view.

I hope I was clear.

Thanks

like image 682
Y2theZ Avatar asked Oct 31 '12 11:10

Y2theZ


2 Answers

For posting a notification use the below code:

[[NSNotificationCenter defaultCenter] postNotificationName:@"Midhun" object:nil];

In the viewDidLoad of the notification listening class add observer like:

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

performTask: is the method which will be called when the notification is observed.

Please refer NSNotification Class Reference

like image 182
Midhun MP Avatar answered Nov 06 '22 16:11

Midhun MP


First options is to store reference to view controller B somewhere (as example in application delegate) and use it to run a method.

The second one is to send notification via [NSNotificationCenter defaultCenter], so controller B set a listener to a notification somewhere (viewDidLoad can be a good place):

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

and controlle A sends it:

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

Note that if you send a notification from a different thread, listener will be executed on the same thread.

like image 23
Mark Pervovskiy Avatar answered Nov 06 '22 16:11

Mark Pervovskiy