Configuring Behavior When Started with UILocalNotification Notifications

Asked 2 years ago, Updated 2 years ago, 67 views

I would like to send a notification using UILocalNotification when the iPhone application is in the background and display a specific view when I launch the application from that notification.

Currently, when you press Open Notification, the app starts normally and the first screen of the app (ViewController) is displayed.How do I view a specific view (SecondViewController) when I launch from a notification?

-(void)setLocalNotification:(NSString*)message
{
    UILocalNotification*notification=[[UILocalNotification alloc] init];
    notification.fireDate=[[NSDate date]dateByAddingTimeInterval:0];
    notification.timeZone = NSTimeZone defaultTimeZone;
    notification.alertBody=message;
    notification.alertAction=@"Open";
    notification.soundName = UILocalNotificationDefaultSoundName;
    notification.applicationIconBadgeNumber=1;

    // Register Notifications
    [[UIAApplication sharedApplication] scheduleLocalNotification:notification];
}

ios objective-c

2022-09-30 20:30

1 Answers

Sample for displaying the SecondViewController in modal format.
AppDelegate.

-(BOOL) application:(UIApplication*) application didFinishLaunchingWithOptions:(NSDictionary*) launchOptions{
  NSDictionary* userInfo= [launchOptions objectForKey: UIAapplicationLaunchOptionsLocalNotificationKey];
  if(userInfo!=nil){
    self showSecondViewController;
  }
  return YES;
}

- (void) application: (UIApplication*) application didReceiveLocalNotification: (UILocalNotification*) notification
{
  if(application.applicationState==UIApplicationStateInactive){
    self showSecondViewController;
  }
}

- (void) showSecondViewController
{
  UIViewController* controller=[SecondViewController alloc] init;
  [self.window.rootViewController presentViewController: controller animated:YES completion:nil];
}

To view the SecondViewController designed on the Storyboard: storyboardWithName:@"Main" depends on the appropriate Storyboard filename, so change it accordingly.(@"Main" for Main.storyboard)

As a reminder, you must set the SecondViewController to the Storyboard ID of the SecondViewController on the Storyboard.

 - (void) showSecondViewController
{
  UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
  UIViewController* controller= [storyboard instantiateViewControllerWithIdentifier:@"SecondViewController";
  [self.window.rootViewController presentViewController: controller animated:YES completion:nil];
}


2022-09-30 20:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.