Changing view from within didReceiveRemoteNotifica

2019-06-01 04:38发布

问题:

Being still new to iPhone development, I am slowly getting there however sometimes the simple things seem to stump me.

My application consists of 7 very different views. It is implemented as a window based app without a navigation controller. Navigation is managed by each view controller individually and I use a central data repository to make data available through the app.

I use :-

DetailView *viewDetail = [[DetailView alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:viewDetail animated:YES];

to change views. Obviously, in all cases, this is executed within the controller of the current view.

HOWEVER, I have now added Push Notification to the app. Upon receipt of a Push, the userInfo data is made available within the main AppDelegate and didReceiveRemoteNotification is executed. I wish to force the application into the Detailview described above, passing it one of the values within userInfo.

Of course, I get a nice SIGABRT as soon as it executes the second line. I assume this is because the currently active view is not self. How do I surrender the current view in favour of the DetailView from within the app delegate? The current view could be ANY of the 7 views, including DetailView, which I wil want to refresh with the new data.

Thanks in advance Chris Hardaker

回答1:

This is a small side note, but the naming convention that you are using is non-standard. Rather than,

DetailView *viewDetail = [[DetailView alloc] initWithNibName:nil bundle:nil];

conventionally, an iOS developer would expect to see the following:

DetailViewController *viewDetail = [[DetailViewController alloc] initWithNibName:nil bundle:nil];

since viewDetail is a subclass of UIViewController rather than UIView.

To answer you main question though, I would use NSNotificationCenter. Basically, this allows any class to post a notification, which more or less just throws out the fact that an event occurred to any class that happens to be listening for it.

So in didReceiveRemoveNotification: you can call:

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

When you allocate your view controllers, run this line:

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

You will need to put a method called pushNotificationReceived: (NSNotification*)aNotification in each of the view controllers to handle the notification. The userInfo dictionary that you passed will be a property of the notification.

Now, when ever the @"pushNotification" notification is sent, your controllers will receive a notification and run the given selector. So you can dismiss the controller or show the detail view or whatever you want.

When you dealloc your view controller, make sure to call

[[NSNotificationCenter defaultCenter] removeObserver:self];