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

前端之家收集整理的这篇文章主要介绍了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;
}
原文链接:https://www.f2er.com/iOS/337271.html

猜你在找的iOS相关文章