2

I want to show notification when app is in forground. Below is the code I did for new usernotificationdelegate method.

In app delegate :

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {

        //iOS 10 handling
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
          if (!error) {
                 NSLog(@"request authorization succeeded!");
          } }];
     } 
}

#pragma mark - User notification delegate
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {

    NSLog(@"willPresentNotification");
    NSLog(@"%@", notification.request.content.userInfo);
    completionHandler (UNNotificationPresentationOptionAlert);
}

And this is my method to trigger local notification

-(void) fireLocalNotification:(NSString *) message
{

    NSLog(@"fire Local Notification");
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {

        //Notification Content
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        content.body =  [NSString stringWithFormat:@"%@",message];
        content.sound = [UNNotificationSound defaultSound];

        //Set Badge Number
        content.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);

        // Deliver the notification in five seconds.
        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger
                                                      triggerWithTimeInterval:1.0f repeats:NO];

        //Notification Request
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"LocalNotification" content:content trigger:trigger];

        //schedule localNotification
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
            if (!error) {
                NSLog(@"add Notification Request succeeded!");
            }
        }];

    }
 }

now after doing this still I am not getting notification in forground.

thanks in advance.

ucMedia
  • 4,105
  • 4
  • 38
  • 46
Nik
  • 1,679
  • 1
  • 20
  • 36
  • refer my answer [from here](http://stackoverflow.com/questions/37324331/local-notification-using-ios-using-swift) it may help you! – Ketan Parmar Oct 14 '16 at 13:05
  • 1
    Does `willPresentNotification` appear in the console log? Do you see the notification alert if the app is _not_ in the foreground? – matt Oct 14 '16 at 13:07
  • Yes @matt, when my app is not in forground that time I see the alert i.e Notification but its not appearing in forground. – Nik Oct 14 '16 at 13:11
  • @Lion, the answers you have mentioned is for UILocalNotification. I wanted to use iOS 10 UserNotification framework. for showing notifications in forground. – Nik Oct 14 '16 at 13:12
  • Also, One more things...I have set the delegate though, UserNotification Delegate is not getting called. – Nik Oct 14 '16 at 13:13
  • You didn't answer my first question. Does `willPresentNotification` appear in the console log? In other words, is your delegate method even being called? Also, are you running on iOS 10? – matt Oct 14 '16 at 13:34
  • My delegate method is not getting called. and yes i am running on iOS 10. but when I am in background then i get the notification for the same. – Nik Oct 14 '16 at 13:41
  • I am showing an alert if the application is in a foreground. I am not able to succeed to show a notification in a foreground. – Nik May 16 '17 at 05:01

5 Answers5

11

Please implement this function :

-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
    completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionSound);
}
mital solanki
  • 2,394
  • 1
  • 15
  • 24
1

For getting notification when the app is in foreground you need to implement following delegate method of UNUserNotificationCenterDelegate in iOS10.

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

    completionHandler([.alert,.badge])
}

For more information you can refer the apple doc. Here is the link:

https://developer.apple.com/documentation/usernotifications/unusernotificationcenterdelegate?language=objc

0

SHOW ALERT TOP OF THE SCREEN

-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
    completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionSound);

}
The iOSDev
  • 5,237
  • 7
  • 41
  • 78
Girish Chauhan
  • 167
  • 1
  • 4
  • -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler { completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionSound); } – Girish Chauhan Mar 22 '17 at 10:41
0

please see this code to handle local notification on foreground. /*****************************/

  UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];

            UNAuthorizationOptions options = UNAuthorizationOptionAlert + UNAuthorizationOptionSound;

            [center requestAuthorizationWithOptions:options
                                  completionHandler:^(BOOL granted, NSError * _Nullable error) {
                                      if (!granted) {
                                          //NSLog(@"Something went wrong");
                                      }
                                  }];

            int dayCounter =5;

            int minute = 48;


           {
                NSDateComponents *components = [[NSDateComponents alloc] init];
                components.weekday = dayCounter;


                 dayCounter++;

                components.hour = 12;
                components.minute = minute;

                UNCalendarNotificationTrigger *trigger =  [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES];

                UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
                objNotificationContent.title = [NSString localizedUserNotificationStringForKey:@"Notification!" arguments:nil];

                objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@"We made a surprise Edit for You" arguments:nil];

                objNotificationContent.sound = [UNNotificationSound defaultSound];

                objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);


                UNNotificationAttachment *attachment = nil;

                NSURL* outputURL = [[NSURL alloc] initFileURLWithPath:filePath];
                NSError *attachmentError = nil;

                attachment = [UNNotificationAttachment attachmentWithIdentifier:@"image"
                                                                            URL: outputURL
                                                                        options:nil
                                                                          error:&attachmentError];
                if (attachmentError) {

                    return;
                }

                objNotificationContent.attachments=@[attachment];

                NSString *identifier = @"UYLLocalNotification";
                UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
                                                                                      content:objNotificationContent trigger: trigger];

                [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
                    if (error != nil) {
                        NSLog(@"Something went wrong: %@",error);
                    }
                    else
                    {
                    }
                }];

/****************************/

// to handle -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{

    UIApplicationState state = [application applicationState];
    if (state == UIApplicationStateActive) {

        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"Reminder" message:notification.alertBody delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Yes", nil];
            alert.tag = 330;
            [alert show];
        });
    }
else{
 // handle for background
}
Ajjjjjjjj
  • 669
  • 4
  • 12
0

For displaying banner message while app is in foreground, use the following method.

Add it to your delegate methods in the AppDelegate and conform to this protocol - UNUserNotificationCenterDelegate

iOS 10, Swift 3:

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler(UNNotificationPresentationOptions.alert)
}
Stan
  • 1,513
  • 20
  • 27