How to register for NSNotification from UILocalNotification?

I have a tab application, and I can say that I want to go to the second tab and pop up an alert at 12:00, even if my application does not work.

I got all the code for UILocalNotification working correctly, but then I thought that the best way to do this is to post a notification from the application delegate:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

    // Add the tab bar controller view to the window and display.
    [window addSubview:tabBarController.view];
    [window makeKeyAndVisible];

    // Handle launching from a notification when the app is NOT running
    UILocalNotification *localNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    if (localNotification) {
        [tabBarController setSelectedIndex:1];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"AlertNotification" object:self];
    }
    return YES;
}

Then in my SecondViewController.m I have:

- (void)viewDidLoad {
  [super viewDidLoad];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popUpAlert:) name:@"AlertNotification" object:nil];
}

But that does not work. I suspect that a notification has been sent while the viewDidLoad from the SecondViewController has not yet been called, is it? Can this be fixed? And do you agree with my approach to use NSNotificationCenterin this case?

Thanks in advance.

+3
source share
3 answers

, awakeFromNib (, SecondViewController xib)

- (void)awakeFromNib {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popUpAlert:) name:@"AlertNotification" object:nil];
}
+3

, . , .

bool , , . [[UIApplication sharedApplication] delegate].

0
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes: UIUserNotificationTypeAlert | UIUserNotificationTypeBadge categories:nil];
[[UIApplication shareApplication] registerUserNotificationSettings: settings];
0
source

Source: https://habr.com/ru/post/1782606/


All Articles