iOS 10,当app在前台时本地通知显示?

时间:2016-10-14 12:56:55

标签: ios objective-c uilocalnotification unusernotificationcenter

我想在app for forground时显示通知。下面是我为新的usernotificationdelegate方法所做的代码。

在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);
}

这是触发本地通知的方法

-(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!");
            }
        }];

    }
 }

现在这样做之后我仍然没有收到forground的通知。

提前致谢

5 个答案:

答案 0 :(得分:11)

请执行此功能:

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

答案 1 :(得分:1)

要在应用程序处于前台时收到通知,您需要在iOS10中实现以下UNUserNotificationCenterDelegate的委托方法。

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

    completionHandler([.alert,.badge])
}

有关详细信息,请参阅apple doc。这是链接:

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

答案 2 :(得分:0)

显示屏幕上方的警告

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

}

答案 3 :(得分:0)

请参阅此代码以处理前台的本地通知。 / ******** /

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

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

//来处理      - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {/ / p>

    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
}

答案 4 :(得分:0)

要在应用程序位于前台时显示横幅消息,请使用以下方法。

将其添加到AppDelegate中的委托方法并符合此协议 - UNUserNotificationCenterDelegate

iOS 10,Swift 3:

 case "CONNECTOR_CONNECTION_FULFILLED":
                state = {
                    ...state,
                    appState: 'loggedIn',
                };
                state.ourPlayer = { ...action.payload.player }

                break;