Reputation: 1553
My problem is the following,
In one of my ViewControllers
, when the user taps a button , I register the device for notifications with this code.
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
Then, in the AppDelegte
, there are two methods. One that receives the token and one that gets the error.
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
And now comes the problem, in didRegisterForRemoteNotificationsWithDeviceToken
I need to send the token to my server, and with it some data that the user has entered in the View
, like its username.
How can I get this data?
Upvotes: 3
Views: 2151
Reputation: 3554
The NSNotificationCenter
will serve you well here. In your AppDelegate's didRegisterForRemoteNotificationsWithDeviceToken
, do this:
[[NSNotificationCenter defaultCenter] postNotificationName:@"RegistrationReceived"
object:token];
And, in your controller's viewDidLoad
,
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(updateRegistrationInfo:)
name:@"RegistrationReceived"
object:nil];
Be sure to implement -updateRegistrationInfo:
(or whatever you want to name it) to receive the NSNotification
and the token, which is passed in as the argument. Also, unregister for the notification when you no longer need it.
- (void)updateRegistrationInfo:(NSNotification *)notification
{
NSString *myObject = [notification object];
...
}
Upvotes: 9
Reputation: 604
You can can add your ViewController
as an instance variable to your AppDelegate
class:
@interface AppDelegate : NSObject <UIApplicationDelegate>
{
@private // Instance variables
UIWindow *mainWindow; // Main App Window
UINavigationController *navigationController;
UIViewController *someViewController;
}
And then add some methods to someViewController
that returns your requested data.
You can assign someViewController in - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
of the AppDelegate
class in this way:
someViewController = [[UIViewController alloc] initWithNibName:nil bundle:nil];
navigationController = [[UINavigationController alloc] initWithRootViewController:someViewController];
Upvotes: 1