当您的应用程序处于forground时,如何在ios 10中生成本地通知?当您的应用处于forground状态时,它无效

时间:2016-12-14 08:56:46

标签: ios objective-c

我在我的应用程序中执行以下步骤

在我的 appdelegate

#import <UserNotifications/UserNotifications.h>


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.


    UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
      center.delegate = (id)self;

    [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {


                              // Enable or disable features based on authorization.
                          }];







    return YES;
}

并在我的 viewcontroller 中生成本地通知的代码

-(IBAction)btnclicked:(id)sender 
{
    UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
    content.title = @"gg";
     content.subtitle = @"ggg";
    content.body = @"hhh";
    content.sound = [UNNotificationSound defaultSound];

    // Deliver the notification in five seconds.
    UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger
                                                  triggerWithTimeInterval:5 repeats:NO];
    UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"2"
                                                                          content:content trigger:trigger
                                      ];

    // Schedule the notification.
    UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        NSLog(@"hii");
    }];





}

现在我的应用程序在前景通知中没有生成。

在ios 9中我使用

 UILocalNotification* localNotification = [[UILocalNotification alloc] init];
    localNotification.soundName = @"Default";
    localNotification.alertBody = @"my notification;)";
    localNotification.fireDate = [NSDate date];
    localNotification.category = @"Email";
    localNotification.repeatInterval = kCFCalendarUnitDay;
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

此代码适用于ios 9,但在ios 10中,UILocalNotification已弃用。

那么当您的应用程序处于前台时,如何在ios 10中生成本地通知?

2 个答案:

答案 0 :(得分:0)

尝试在iOS10中使用UNUserNotificationCenterDelegate

  

iOS 10添加了UNUserNotificationCenterDelegate协议,用于在您的应用位于前台时处理通知。

Hope this will help

答案 1 :(得分:-1)

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

iOS 10,Swift 3:

//当app收到前台推送通知时,将调用此方法

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) 
{
    completionHandler(
       [UNNotificationPresentationOptions.alert,
        UNNotificationPresentationOptions.sound,
        UNNotificationPresentationOptions.badge])
}