ios – 从哪个UILocalNotification中检测到一个应用程序被打开

在某些情况下,我的iOS应用程序必须同时触发多个UILocalNotification.我想决定用户点击的UILocalNotification.当用户单击UILocalNotification时,该应用程序处于非活动状态或在后台.问题是该方法
func application(application: UIApplication,didReceiveLocalNotification notification: UILocalNotification) {

被称为每个触发的UILocalNotification.所以当应用程序变得活跃时,这个方法被多次调用,因为我收到了多个UILocalNotification.有没有办法确定哪个UILocalNotification是应用程序打开的原因?对applicationState的检查不起作用,因为当应用程序处于非活动状态或在后台时,所有UILocalNotification都已被接收.

非常感谢!

编辑:
作为一个很好的例子:当您从两个不同的组A和B收到WhatsApp消息,并从组A中选择推送通知时,应用程序打开后立即显示. WhatsApp和我的用例之间的区别是我有本地通知.

解决方法

在计划通知时,您可以为通知userinfo设置一些唯一的ID.
UILocalNotification *notif = [[UILocalNotification alloc] init];
    notif.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];
    notif.timeZone = [NSTimeZone defaultTimeZone];

// set the your data with unique id
    NSMutableDictionary *dict=[NSMutableDictionary new];
    [dict setObject:Id forKey:@"id"];

// assignt the dictionary to user info
    notif.userInfo=dict;


    notif.alertBody = @"test Notification";
    notif.soundName = UILocalNotificationDefaultSoundName;


    [[UIApplication sharedApplication] scheduleLocalNotification:notif];

你可以通过didReceiveLocalNotification获得用户信息

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    if ([[notification.userInfo valueForKey:@"id"] isEqualToString:@"1"])
    {
        NSLog(@"notification id %@",[notification.userInfo valueForKey:@"id"]);
    }
    else if ([[notification.userInfo valueForKey:@"id"] isEqualToString:@"2"])
    {
        NSLog(@"notification id %@",[notification.userInfo valueForKey:@"id"]);
    }

    ////// or /////

    if ([notification.userInfo valueForKey:@"id"] )
    {
        NSLog(@"id of notification %@",[notification.userInfo valueForKey:@"id"]);
    }

}

来自didFinishLaunchingWithOptions

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    if ([launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey])
    {
       UILocalNotification *notif=[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
        NSLog(@"notif.userInfo  %@",notif.userInfo);

//        notif.userInfo  {
//            id = 2;
//        }

    } 


        return YES;
}

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...