iOS / Obj-C – 没有计时器的Fire本地通知?

我想在我的iOS应用程序中设置一些本地通知,但是我似乎在实现这些时发现的每个教程似乎只允许我根据计时器发出通知(参见下面的示例代码)? 是否可以在将新数据加载到UITableView时触发本地通知? 对于一般性问题很抱歉,但我似乎无法找到关于此的大量文档。 如果我的用户点击屏幕时只抓取数据,我也不确定如何才能做到这一点? 例如,在ViewController的viewDidLoad中抓取/更新数据?

-(void)viewDidLoad { UILocalNotification *localNotification = [[UILocalNotification alloc] init]; localNotification.fireDate = dateTime; localNotification.alertBody = [NSString stringWithFormat:@"Alert Fired at %@", dateTime]; localNotification.soundName = UILocalNotificationDefaultSoundName; localNotification.applicationIconBadgeNumber = 1; [[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; } 

首先,您应该考虑从iOS 10开始不推荐使用您正在使用的UILocalNotification类。自iOS 10以来,本地和远程通知之间没有区别。

在UserNotifications框架(iOS 10.0 +,Swift | Objective-C)中,人们不会像在Apple的类似框架/ API的某些先前实现中那样创建UNNotification的实例。 相反, UNNotificationCenter的实例负责创建通知对象,并在收到新通知时以及显示默认UI之前调用委托方法。 有关符合UNUserNotificationCenterDelegate协议要求的更多详细信息,请参阅Apple的文档 。 我经常最终使用AppDelegate作为符合该协议的类

现在回到这个问题。 要首先从应用程序中启动通知创建,您应该创建一个触发器(在您的情况下,您可能希望使用UNTime​Interval​Notification​Trigger ),然后创建通知请求并最终将请求添加到通知中心单例可以通过调用UNUserNotificationCenter.current()来访问。

 let content = UNMutableNotificationContent() content.title = "Alert Fired" 

创建一个触发器,用于确定UNUserNotificationCenter将调用通知的时刻

 let trigger = UNTime​Interval​Notification​Trigger(timeInterval: 0, repeats: false) 

创建通知请求。 您只创建那些调用本地通知,因为iOS负责为传入的推送通知创建请求对象。

 let request = UNNotificationRequest(identifier: "FiveSecond", content: content, trigger: trigger) 

现在,我们必须将我们的请求添加到与我们的应用相关联的当前通知中心。

 let center = UNUserNotificationCenter.current() center.add(request, withCompletionHandler: nil) 

在我们的情况下,通知将由UNUserNotificationCenter立即触发。

您可以使用postNotificationName方法,如下所示:

 MyCustomObject *customObject = [MyCustomObject new]; [[NSNotificationCenter defaultCenter] postNotificationName:@"Your notification name" object:customObject]; 

处理从发布的通知中发出的对象看起来像这样。 显然,我只是在这里登录,但你可以随心所欲地处理它。

 - (void)methodToProcessNotificationData:(NSNotification *)notification { NSLog(@"%@",notification.object); } 

当你想要一个类来监听通知时,你可以做类似下面的代码块。 这会将观察者添加到类中,为其提供要调用的方法(在此实例中为methodToProcessNotificationData)以及您希望侦听的通知名称。

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(methodToProcessNotificationData:) name:@"Your notification name" object:nil]; 

您可以使用以下方法[1]代替:

 - (void)postNotificationName:(NSNotificationName)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo; 

[1] https://developer.apple.com/reference/foundation/nsnotificationcenter/1410608-postnotificationname?language=objc

只要您想要发出本地通知,您就可以将时间设置为[NSDate date] 。 它会在当前时间发出通知。

首先要考虑的是你需要本地本地通知

 // Handle launching from a notification if(IOS_VERSION<10) { UILocalNotification *locationNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]; if (locationNotification) { // Set icon badge number to zero application.applicationIconBadgeNumber = 0; } if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]) { [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge| UIUserNotificationTypeSound categories:nil]]; } 

}其他{

 [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) { // Enable or disable features based on authorization. }]; 

}

最后的事情

  if(IOS_VERSION<10){ [[UIApplication sharedApplication] cancelAllLocalNotifications]; NSLog(@"LocalNotifications]count %d",(int) [[[UIApplication sharedApplication] scheduledLocalNotifications]count]); NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar] ; NSDate *now = [NSDate date]; NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:now]; [components setHour:15]; [components setMinute:35]; UILocalNotification *notification = [[UILocalNotification alloc]init]; notification.fireDate = [calendar dateFromComponents:components]; notification.repeatInterval = NSCalendarUnitDay; notification.alertBody =@"message"; notification.applicationIconBadgeNumber = 0; notification.soundName = UILocalNotificationDefaultSoundName; [[UIApplication sharedApplication] scheduleLocalNotification:notification]; }else{ [[UNUserNotificationCenter currentNotificationCenter] removeAllPendingNotificationRequests]; NSLog(@"LocalNotifications]count %d",(int) [[[UIApplication sharedApplication] scheduledLocalNotifications]count]); NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar] ; NSDate *now = [NSDate date]; NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:now]; [components setHour:15]; [components setMinute:35]; UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init]; // objNotificationContent.title = [NSString localizedUserNotificationStringForKey:NotificationHeading arguments:nil]; objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@"message" arguments:nil]; objNotificationContent.sound = [UNNotificationSound defaultSound]; /// 4. update application icon badge number objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber]); // UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger // triggerWithTimeInterval:60 repeats:YES]; UNCalendarNotificationTrigger *trigger2 = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES]; UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond" content:objNotificationContent trigger:trigger2]; /// 3. schedule localNotification UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (!error) { NSLog(@"Local Notification succeeded"); } else { NSLog(@"Local Notification failed"); } }]; }