简体   繁体   中英

Access ViewController from AppDelegate

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?

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];
    ...
}

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM